Java Reference
In-Depth Information
345
Q UALITY T IP 8.2: Minimize Side Effects
In an ideal world, all methods would be accessors that simply return an answer
without changing any value at all. (In fact, programs that are written in so-called
functional programming languages, such as Scheme and ML, come close to this
ideal.) Of course, in an object-oriented programming language, we use objects to
remember state changes. Therefore, a method that just changes the state of its
implicit parameter is certainly acceptable. Although side effects cannot be
completely eliminated, they can be the cause of surprises and problems and should
be minimized. Here is a classification of method behavior.
ȗ
Accessor methods with no changes to any explicit parametersȌno side
effects. Example: getBalance .
ȗ
Mutator methods with no changes to any explicit parametersȌan acceptable
side effect. Example: withdraw .
ȗ
Methods that change an explicit parameterȌa side effect that should be
avoided when possible. Example: transfer .
ȗ
Methods that change another object (such as System.out)Ȍa side effect that
should be avoided. Example: printBalance .
Q UALITY T IP 8.3: Don't Change the Contents of
Parameter Variables
As explained in Common Error 8.1 and Advanced Topic 8.1 , a method can treat its
parameter variables like any other local variables and change their contents.
However, that change affects only the parameter variable within the method
itselfȌnot any values supplied in the method call. Some programmers take
Ȓadvantageȓ of the temporary nature of the parameter variables and use them as
Ȓconvenientȓ holders for intermediate results, as in this example:
public void deposit(double amount)
{
// Using the parameter variable to hold an intermediate value
amount = balance + amount; // Poor style
Search WWH ::




Custom Search