|Ada 95 Quality and Style Guide||Chapter 4|
Use a function when the subprogram's primary purpose is to provide a single value.
Minimize the side effect of a function.
Consider using a parameterless function when the value does not need to be static.
Use a parameterless function (instead of a constant) if the value should be inherited by types derived from the type.
Use a parameterless function if the value itself is subject to change.
Although reading a character from a file will change what character is read next, this is accepted as a minor side effect compared to the primary purpose of the following function:function Next_Character return Character is separate;
However, the use of a function like this could lead to a subtle problem. Any time the order of evaluation is undefined, the order of the values returned by the function will effectively be undefined. In this example, the order of the characters placed in Word and the order that the following two characters are given to the Suffix parameters are unknown. No implementation of the Next_Character function can guarantee which character will go where:Word : constant String := String'(1 .. 5 => Next_Character); begin -- Start_Parsing Parse(Keyword => Word, Suffix1 => Next_Character, Suffix2 => Next_Character); end Start_Parsing;
Of course, if the order is unimportant (as in a random number generator), then the order of evaluation is unimportant.
The following example shows the use of a parameterless function instead of a constant:type T is private; function Nil return T; -- This function is a derivable function Default return T; -- operation of type T. Also derivable, -- and the value can be changed by -- recompiling the body of the function
This same example could have been written using constants:type T is private; Nil : constant T; Default : constant T;
A side effect is a change to any variable that is not local to the subprogram. This includes changes to variables by other subprograms and entries during calls from the function if the changes persist after the function returns. Side effects are discouraged because they are difficult to understand and maintain. Additionally, the Ada language does not define the order in which functions are evaluated when they occur in expressions or as actual parameters to subprograms. Therefore, a program that depends on the order in which side effects of functions occur is erroneous. Avoid using side effects anywhere.
|< Previous Page||Search||Contents||Index||Next Page >|