2.1.2 - Inputs, outputs and preconditions
Before choosing an algorithm, make its problem precise. You will identify the data a solution needs, the form of its results, and the conditions that must hold before it starts.
Specify the input and output contract
An input is data supplied to a solution; an output is data or an effect produced by it. A useful contract states their meaning, types, units and format, rather than merely naming an input device and a screen.
Consider a parking-charge calculator. A user enters the start and finish time; a stored price table supplies the tariff. Keyboard entries are inputs, but so is relevant stored data: not every input is typed during the current run. The output may be a numerical fee for another component, a formatted on-screen message and a printed receipt. Digital and hard-copy outputs can carry the same result in different forms.
For an original simplified policy, charge 3 units per started hour, with zero charge for zero duration. To remove ambiguity, define the inputs as integer start and finish minutes after midnight on the same day, with finish at least start. The output is an integer fee in currency units. For start 600 and finish 665, duration is 65 minutes: two started hours cost 6 units. The displayed string might be Fee: 6 units; that formatting is a separate decision from the numeric fee.
The policy has to say what happens across midnight or for a missing time. Without that information a programmer could devise several incompatible solutions. Clarify the required result before choosing representations or operations.
State the conditions that make the solution valid
A precondition is a condition required to hold before an operation or algorithm is used. It can concern the data, the starting state, or an available resource. It is not the result that the algorithm promises to produce.
Suppose a routine returns the largest item by setting largest to the first list item, then comparing the remaining items. Its precondition is that the list is non-empty and its items are comparable numbers. Starting with the first item avoids an incorrect assumption that zero is always a suitable maximum. For [-8, -3, -11], the routine returns -3. With an empty list there is no first item; the stated routine has no valid starting value.
Another routine repeatedly halves a search interval by comparing its middle item with a target. To safely discard one half, it needs a sorted list under the same comparison rule. This is a precondition of that method, not of every possible search: a method that checks each item can search an unsorted list. The algorithm choice and preconditions must agree.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account