Data Definitions in Program Design

Before you write a function, decide what its inputs can represent. A data definition specifies the permitted forms of data and explains what those forms mean. It connects a problem description to the values your program handles. Once you know whether a value is a single number, a group of fields, or one of several alternatives, you can plan the function's structure without guessing which information will be available.

Describe values precisely

A useful definition gives more than a programming-language type. An integer might represent a parcel count, a temperature, or an identifier. These interpretations permit different values and operations. State the meaning, units where relevant, and restrictions that affect the computation.


Common data shapes suggest different ways to work with a value:


Data shape

Information supplied by the definition

Consequence for a function

Basic value

One value with a stated meaning, such as distance in kilometres

Use that value directly

Enumeration

A fixed set of named choices

Distinguish relevant choices

Record

Named fields grouped into one value

Select the fields needed for the result

Tagged alternative

One of several labelled forms, each with its own fields

Check the label before using fields specific to a form

Sequence

An ordered collection whose elements follow a stated definition

Process the relevant elements using that definition


These shapes can be combined. For example, a courier alternative can contain a record of distance and parcel count. A sequence can contain many such collection methods.


Suppose a collection method is either Pickup, with no additional fields, or Courier(distance_km, parcels), where distance is nonnegative and parcels is a positive integer. The notation names the form and its fields; it does not require a particular programming language. A Python dictionary could represent the label using a kind entry.


A collection method has either a Pickup alternative or a Courier alternative with distance and parcel fields.


Let the shape guide the function

A function template is a partial function structure derived from the input's data definition. It identifies possible cases and available components before you supply the calculation. It is a starting point for reasoning, rather than a finished algorithm.


For alternatives, inspect the tag before accessing fields that belong to only one form. For a record, select its named components. For a sequence, account for its elements. When shapes are nested, apply these ideas at each relevant level.


Suppose collection charges are zero for pickup. Courier charges include 4.00 dollars, 1.50 dollars per kilometre, and 0.75 dollars per parcel. With charge CC in dollars, distance dd in kilometres, and parcel count pp, the rule is


C={0for Pickup,4.00+1.50d+0.75pfor Courier.C = \begin{cases} 0 & \text{for Pickup},\\ 4.00 + 1.50d + 0.75p & \text{for Courier}. \end{cases}


The two alternatives suggest two cases. Only the courier case needs distance and parcel count.


Example: A courier collection travelling 2.0 kilometres with four parcels costs 4.00+1.50(2.0)+0.75(4)=10.004.00 + 1.50(2.0) + 0.75(4) = 10.00 dollars. A pickup value does not need artificial distance or parcel fields to support its zero charge.



Respect the definition's boundary

A template assumes the input satisfies its data definition. A courier value missing its parcel count is outside the definition, even if its tag is correct. If outside input may be malformed, check it before relying on the promised fields.


Absence also has meaning. A field that does not exist is different from a field whose value is zero. Similarly, a missing reading differs from a measured temperature of zero degrees Celsius.



A template need not force unnecessary work. If every alternative provides the same identifier and a function only returns that identifier, selecting it directly may be sufficient. Branching is needed when the required access or behaviour depends on the form.

What to remember

  • State permitted forms, field meanings, units, and relevant restrictions.
  • Derive cases and component access from the data shape.
  • Check the active alternative before using its exclusive fields.
  • Let the requested result determine which available information you actually use.

Example: Designing a Print-Job Charge

A campus print studio represents each job with a Python dictionary. A record groups named fields into one value. Every job has a kind field identifying one of these alternatives:


Kind

Additional fields

Restrictions

draft

pages

Positive integer page count

poster

width_cm, height_cm, copies

Positive integer dimensions in centimetres and positive integer copy count


Draft printing costs 0.08 dollars per page. Poster printing costs 0.002 dollars per square centimetre per copy. There are no additional fees.


A customer orders three copies of a poster that is 40 cm wide and 60 cm high.


Example: Use the data definition to represent the order, plan the function, and calculate its charge.


a) Write the dictionary representing this order.


First identify the selected alternative: the order is for posters, so its kind is poster. This form requires width, height, and copy count. The dimensions are already in the centimetres required by the field names, and all three values satisfy the positive-integer restrictions.


The complete representation is:


Python
{"kind": "poster", "width_cm": 40, "height_cm": 60, "copies": 3}


No pages field is needed because that field belongs to the Draft alternative.


b) Write a function template that separates the alternatives and makes their fields available, without yet calculating a charge. Assume every input satisfies the data definition.


First inspect kind, since the required fields depend on the alternative. In the Draft case, select pages. In the Poster case, select width, height, and copies. Each ... is a placeholder for the calculation still to be written.


Python
def charge(job):
    if job["kind"] == "draft":
        pages = job["pages"]
        ...
    elif job["kind"] == "poster":
        width = job["width_cm"]
        height = job["height_cm"]
        copies = job["copies"]
        ...


This template covers the two permitted forms. Its field accesses are justified by the valid-input assumption and the preceding kind check.


c) Calculate the customer's total charge in dollars to two decimal places.


First select the Poster calculation because the order's kind is poster. Its charge depends on area per copy and the number of copies.


The area of one copy is ________:


A=wh=(40 cm)(60 cm)=2400 cm2.A = wh = (40\ \text{cm})(60\ \text{cm}) = 2400\ \text{cm}^2.


Next account for all three copies. The total printed area is ________:


Atotal=3(2400 cm2)=7200 cm2.A_{\text{total}} = 3(2400\ \text{cm}^2) = 7200\ \text{cm}^2.


Finally multiply by the rate per square centimetre:


C=(0.002 dollarscm2)(7200 cm2)=14.40 dollars.C = \left(0.002\ \frac{\text{dollars}}{\text{cm}^2}\right)(7200\ \text{cm}^2) = 14.40\ \text{dollars}.


The total charge is 14.40 dollars. The square-centimetre units cancel, and multiplying by three copies ensures that the result covers the entire order rather than one poster.

A monitoring program defines a report as either Offline(reason), where reason is nonempty text, or Online(temp_c, battery_percent), where both fields are numbers and battery percentage is between 0 and 100 inclusive. Which value satisfies this data definition?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A developer is documenting the permitted shapes of program inputs before writing functions. Match each data-shape name to the description that best explains its structure.

Match each term
A.

A group of named components stored together as one value

B.

A fixed set of named choices, each representing one permitted value

C.

An ordered collection of elements that each satisfy a stated definition

D.

A choice between labelled forms that may provide different components

Sequence

Record

Enumeration

Tagged alternative

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A delivery service defines a shipment as either Standard(mass_kg) or Refrigerated(mass_kg, hours). Mass is positive, and refrigeration hours are nonnegative. Every shipment costs 2.00 dollars plus 1.80 dollars per kilogram. Refrigerated shipments additionally cost 0.60 dollars per refrigeration hour.


Find the charge for Standard(mass_kg=4.5) and the charge for Refrigerated(mass_kg=3.0, hours=5). Give each charge in dollars to two decimal places.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice