Program Design in a Nutshell: 1)
The design recipe for functions/methods:
|
Write down in English the purpose statement for the function/method, describing what data it will consume, and what values it will produce. Add a contract/signature that specifies that data types for all inputs and the output.
Make examples of the use of the function/method with the expected outcomes.
Make an inventory of all data, data parts, and functions/methods available to solve the problem.
Now design the body of the function/method. If the problem is too complex, use a wish list for tasks to be deferred to helper functions.
Run tests that evaluate your examples. Add more tests if needed.
If every function produces a new value, the result, then the entire design process is very straightforward:
Tests are simple, as they only verify that the result matches the expected value.
Function composition comes naturally — the result of any function application can be used in further computations.
the order of computation does not affect the result. (However, a function or a data item must be defined before it can be used.)
To test methods that change state (have side effects) you have to do the following:
Setup: Initialize the data needed to invoke the method (and to verify the results)
Invoke the method to be tested.
Test the expected results, and the expected changes (effects).
Tear-down: Reset the data that has been used to their original values (if the data will be used again in other tests).
More design recipes will be added as needed...