4.1.11 Explain the need for pre-conditions when executing an algorithm.
4.1.12 Outline the pre- and post-conditions to a specified problem.
4.3.12 Discuss the need for sub-programmes and collections within programmed solutions.
4.3.13 Construct algorithms using pre- defined sub-programmes
"to think carefully about what might happen in the future, or to make plans for things you want to do in the future"
Thinking ahead in programming can be as simple as providing proper documentation to programs to make them readable and understandable for other programmers.
Specifically providing information in pre-condition and post-condition.
Providing post condition information for a method or function requires a programmer to think ahead and identify what result is expected when the program is executed.
Method documentation is in the form of documentation comments (/** */ ) that appear just above the method declaration.
/**
* Print a bar of asterisks across the screen.
* pre: length > 0
* post: Bar drawn of length characters, insertion point moved to next line.
*/
public static void drawBar(int length) {
for (int i = 0; i < length; i++) {
System.out.print("*");
}
System.out.println();
}
The assumptions, or initial requirements, of a method are stated in the documentation in a section called the precondition , or just pre.
Note that the pre for drawBar() states that length must be greater than 0, but not that length must be an int. Information that the compiler will verify, such as data types, should not be stated in method documentation.
The postcondition section of the documentation, or post, states what must be true after the method has been executed. However, the post should not state how the method accomplished its task.
A method may not have a precondition, but every method must have a postcondition.
/**
* Calculates the cube of a number.
* pre: none
* post: x cubed returned
*/
public static double cubeOf(double x) {
double xCubed;
xCubed = x * x * x;
return xCubed;
}