90 min

Contracts, tests and decomposition

Write the contract of a function, test it on its boundaries, repair a broken function, split a program into one-job functions, and build the charging station controller.

A function contract

A battery charging station may charge only when two things are true: the battery voltage is between 12000 and 14500 millivolts, and the battery is not hotter than 45 °C. We put this rule in one function, is_voltage_safe.

Before writing the code, write the function's contract (חוזה פונקציה): the agreed input, output and rule.

is_voltage_safe
Inputint voltage_mV, int temperature_c
Rule12000 <= voltage_mV <= 14500 and temperature_c <= 45
Output1 when safe, 0 when not safe

Every caller uses the same rule, and anyone who calls the function knows what to send and what comes back without reading its body. The rule can also be tested by itself.

The rule in C

int is_voltage_safe(int voltage_mV,
                    int temperature_c)
{
    int voltage_ok;
    int temperature_ok;
 
    voltage_ok = voltage_mV >= 12000 &&
                 voltage_mV <= 14500;
    temperature_ok = temperature_c <= 45;
 
    return voltage_ok && temperature_ok;
}

Two local variables hold the two parts of the rule. Each part can be read and checked on its own, and the return line joins them with &&.

Trace the call is_voltage_safe(13000, 46):

VariableValueWhy
voltage_mV13000copy of the first argument
temperature_c46copy of the second argument
voltage_ok113000 is between 12000 and 14500
temperature_ok046 is more than 45
returned value01 && 0 is 0

The voltage is fine, but the battery is too hot: the function returns 0.

Step through the call with 13000 and 46: the frame fills in, and the function returns 0.Open full screen

Boundary tests

Mistakes in rules hide on the edges. If you write < where the rule needs <=, or 1450 instead of 14500, a test in the middle (13000 mV, 25 °C) still passes. So we test each edge three ways: just below, on, and just above. These are boundary tests (בדיקות גבול).

voltage_mVtemperature_cexpectedwhat it checks
11999250just below the low edge
12000451on the low edge, and on the temperature edge
14500451on the high edge
14501250just above the high edge
13000460temperature just above 45

For a function that accepts 10 through 20, the smallest useful set is 9, 10, 20 and 21, plus one value in the middle such as 15.

Click a test in the table to see where it sits on the voltage and temperature lines.Open full screen

Guided practice: temperature conversion

Fill in the return expression. The formula is F = C × 9/5 + 32.

double celsius_to_fahrenheit(double c)
{
    return ______________________;
}
 
int main(void)
{
    double result;
    result = celsius_to_fahrenheit(25.0);
    printf("%.1f\n", result);
    return 0;
}

Checks: 0.0 gives 32.0, 25.0 gives 77.0, and -40.0 gives -40.0.

Answer

Try it yourself first, then open the solution step by step.

    Guided practice: larger value

    int larger(int a, int b)
    {
        if (a >= b) {
            return a;
        }
        return b;
    }

    Trace three calls:

    Calla >= bLine that runsResult
    larger(4, 9)falsereturn b;9
    larger(9, 4)truereturn a;9
    larger(7, 7)truereturn a;7

    A return ends the function at once: when a >= b, the line return b; never runs. The tie returns a, but the value is the same.

    Debugging: average

    This program should print 7.5. It has two separate faults. Find both before you edit.

    int average(int a, int b);
     
    int main(void)
    {
        double result = average(7, 8);
        printf("%.1f\n", result);
        return 0;
    }
     
    double average(int a, int b)
    {
        return (a + b) / 2;
    }
    Answer

    Try it yourself first, then open the solution step by step.

      Step through the two faults and the repaired program.Open full screen

      One function, one responsibility

      The charging station controller has four jobs: read the input, check safety, select the charging current, and print a report. Written all in main, the jobs are tangled together, and to test the safety rule you must run everything.

      Split into functions, each job gets a name and one place to change:

      JobFunction
      reads inputread_input
      checks safetyis_voltage_safe
      selects currentcharge_current_ma
      prints reportprint_report

      Splitting a program into functions is called decomposition (חלוקת תוכנית). The number of functions is not the goal. A separate function helps when it names one meaningful job, removes repetition, or makes testing easier.

      A good name says what the function returns. Compare check, thing and is_temperature_safe: only the last one tells you what 1 means. A name that starts with is_ reads like a yes or no question, so the call reads like a sentence: if (is_temperature_safe(t)).

      The charging station mission

      This is the team mission of the unit (practice question 30).

      • Write int is_voltage_safe(int voltage_mV, int temperature_c): 1 for 12000 to 14500 mV and at most 45 °C, otherwise 0.
      • Write int charge_current_ma(int voltage_mV): 2000 below 13500 mV; 1000 from 13500 through 14500; otherwise 0.
      • main reads the voltage and the temperature once.
      • Print SAFE <current> when safe. Otherwise print STOP 0.
      • Submit the code and the output of every acceptance test.

      The acceptance tests (בדיקות קבלה) decide when the mission is done. Each boundary proves one part of the contract:

      voltagetemperaturesafecurrentoutput
      119992500STOP 0
      120004512000SAFE 2000
      135002511000SAFE 1000
      145004511000SAFE 1000
      145012500STOP 0
      130004600STOP 0
      Click each test and follow it through the two functions. When the voltage is not safe, charge_current_ma is never called.Open full screen

      Key words

      EnglishHebrewMeaning
      contractחוזה פונקציהthe agreed input, output and rule of a function
      boundary testבדיקת גבולa test just below, on or just above an edge
      acceptance testבדיקת קבלהa required test the program must pass
      decompositionחלוקת תוכניתsplitting a program into functions
      responsibilityאחריותthe one job a function does
      integer divisionחילוק שלמיםint / int drops the fraction: 15 / 2 is 7
      conflicting declarationsהצהרות סותרותa prototype and a definition that do not match

      Practice

      The full set of questions with answers is on the practice page. Homework: questions 15 to 22, each with its tests.