Sponsored Link •
Three kinds of methods
The remainder of this article will discuss method design techniques that are concerned with the data a method uses or modifies. In this context, I'd like to identify and name three basic types of methods in Java programs: the utility method the state-view method, and the state-change method.
The utility method
A utility method is a class method that doesn't use or modify the state (class variables) of its class. This kind of method simply provides a useful service related to its class of object.
Some examples of utility methods from the Java API are:
public static int toString(int i)-- returns a new
Stringobject representing the specified integer in radix 10
public static native double cos(double a)-- returns the trigonometric cosine of an angle
The state-view method
A state-view method is a class or instance method that returns some view of the internal state of the class or object, without changing that state. (This kind of method brazenly disregards the Heisenberg Uncertainty Principle -- see Resources if you need a refresher on this principle.) A state-view method may simply return the value of a class or instance variable, or it may return a value calculated from several class or instance variables.
Some examples of state-view methods from the Java API are:
public String toString()-- returns a string representation of the object
public byte byteValue()-- returns the value of the
Integerobject as a byte
public int indexOf(int ch)-- returns the index within the string of the first occurrence of the specified character
The state-change method
The state-change method is a method that may transform the state of the class in which the method is declared, or, if an instance method, the object upon which it is invoked. When a state-change method is invoked, it represents an "event" to a class or object. The code of the method "handles" the event, potentially changing the state of the class or object.
Some examples of state-change methods from the Java API are:
public StringBuffer append(int i)-- appends the string representation of the
intargument to the
public synchronized void clear()-- clears the
Hashtableso that it contains no keys
public final synchronized void addElement(Object obj)-- adds the specified component to the end of the
Vector, increasing its size by one