Method_types_in_java
Method_types_in_java
net/publication/228742589
CITATIONS READS
5 8,071
1 author:
Dirk Riehle
Friedrich-Alexander-University Erlangen-Nürnberg
181 PUBLICATIONS 3,511 CITATIONS
SEE PROFILE
All content following this page was uploaded by Dirk Riehle on 04 May 2014.
Abstract
As Java developers, we talk about query methods, command methods, and factory methods. We talk about
convenience methods, helper methods, and assertion methods. We talk about primitive methods, composed methods,
and template methods.
Obviously, we have a rich vocabulary for talking about methods of a class or interface. We use this vocabulary to
quickly communicate and document what a method does, who it may be used by, and how it is implemented.
Understanding this vocabulary is key to fast and effective communication among developers.
This article presents three method type categories and nine key method types that we use in our daily work. It
presents them using a running example and then catalogs them for use as part of a shared vocabulary. Each of the
method types comes with its own naming convention. Mastering this vocabulary helps us better implement our
methods, better document our classes and interfaces, and communicate more effectively.
1 Introduction
We use a common class design pattern to illustrate the different types of methods: the combination of an interface
with an abstract superclass and two concrete subclasses that add to the superclass and that implement the interface.
The example is a Name interface with a complementing abstract superclass AbstractName and two concrete
implementations StringName and VectorName. This example is rich enough to provide all the core types of methods
that make up large parts of our everyday vocabulary when we talk about methods.
Walking through this design and discussing the methods lets us encounter three main categories of method types:
query methods, mutation methods, and helper methods. We then use specific method types like conversion method
or assertion method to better design the interface and classes as well as to better document them. Using the naming
conventions associated with each method type lets us communicate more efficiently.
The method types discussed in this article describe the purpose of a method as it serves a client. A follow-up article
discusses the additional properties a method may have. Method properties include being a primitive, hook, or
convenience method. Every method has exactly one method type, but it may have several method properties. So, a
method may be of type “get method” and have properties “primitive” and “hook”.
Consider the design example now: we frequently give names to objects so that we can store the objects under these
names and retrieve them later. Names may be as simple as a single string, and they may be as complex as a multi-part
URL. Names we use frequently are class, interface, and package names, for example, “java.lang.String”. Such a name
consists of several parts, called name components. The name components of “java.lang.String” are “java”, “lang”,
and “String”. Generally speaking, we can view a name as a sequence of name components. In the example, we
represent each name as a Name object and each name component as a String object.
2
package org.riehle.Name;
/**
* Returns a simple human readable description. May not show all
* fields but is guaranteed to be distinct for distinct values.
*/
public String asString();
public String asStringWith(char delimiter);
/**
* Gets/sets a name component.
*/
public String component(int index) throws InvalidIndexException;
public void component(int index, String comp) throws InvalidIndexException;
/**
* Appends/prepends/inserts/removes a name component.
*/
public void prepend(String comp);
public void append(String comp);
public void insert(int index, String comp) throws InvalidIndexException;
public void remove(int index) throws InvalidIndexException;
/**
* Returns delimiter/escape char/string used by this name object.
*/
public char delimiterChar();
public String delimiterString();
public char escapeChar();
public String escapeString();
/**
* Returns true if objects are equal.
* Objects may be of different classes.
*/
public boolean isEqual(Name name);
/**
* Returns true if name.isEqual("")
*/
public boolean isEmpty();
/**
* Returns name component enumeration.
*/
public NameEnumeration components();
/**
* Returns number of components in this name object.
*/
public int noComponents();
3
Browsing over the methods, we can see immediately two main categories of methods: query methods and mutation
methods.
Query methods are methods through which you request some information, but that don’t change the state of the
object. Examples of query methods are “String component(int)” that requests a specific name component and
“boolean isEmpty()” that asks whether the name object is equal to “”.
Mutation methods are methods that do something to the object (change its state). Typically, they do not return
anything (for exceptions, see below). Examples of mutation methods are “void component(int i, String c)” that sets
the component on index i to value c and “void remove(int i)” that removes the component on index i.
Finally, there is a third category of method types: helper method. You may already have noticed the
“NameEnumeration components()” method. It creates a NameEnumeration object for iterating over all name
components of a name object. This method is a factory method [3]. A factory method is neither a query nor a
mutation method, because it does not return information about the object being queried nor does it change the
object. A factory method is a helper method, which is a third category of method types.
3 Purpose of a method
So we have three main categories of method types: query methods, mutation methods, and helper methods. Query
methods return information about the object, but don’t change its state. Mutation methods change the object’s state
(cause a state transition), but do not return anything. Helper methods neither return information about the object nor
do they change its state, but they carry out some helper task.
These three method type categories answer what a method is good for, what its purpose is. Other valid perspectives
on methods are who may access a method (accessibility, visibility) and how it is implemented. This article discusses
method types. It leaves out method properties, which will be discussed in a follow-up article.
The purpose point of view comprises the largest number of method types. Table 1 shows all method types that are
discussed in this article. This list is by no means exhaustive! However, it covers most of the method types I have
worked with and I believe that it captures the most important ones.
conversion method
One rule of good Java interface design is to make a method provide exactly one service and not to overload it with
too many tasks. Kent Beck programmatically states: “Divide your program into methods that perform one identifiable
task” [2].
The main advantage of keeping methods simple and well focused is that you make your methods easier to
understand. You also make them easier to use, because a method that is easier to understand is easier to use. In
addition, small methods make a system more flexible. If you break up behavior into many small methods, you can
more easily change your system. You can more easily use small methods and compose them to larger methods. You
can also override smaller methods in subclasses more easily than you can override large methods.
4
In general, this rule leads to a method being either in the query method, mutation method, or helper method category.
However, no rule is without exceptions, which we discuss after the discussion of the method type categories.
We can distinguish four different query method types: get methods, boolean query methods, comparison methods,
and conversion methods.
• Get method (or getter for short). A get method is a query method that returns a (logical) field of the object. The
field may be a technical field or it may be a logical field, derived from other fields. Examples of get methods are
“String component(int)” to retrieve a specific name component and “char delimiterChar()” to retrieve the default
delimiter char used to separate name components when representing the name as a single string.
• Boolean query method. A boolean query method is a query method that returns a boolean value. Examples of
boolean query methods are “boolean isEqual(Name)” and “boolean isEmpty()”. Boolean query methods are so
frequent and have special naming conventions that I decided to give them an extra name rather than just calling
them query method.
• Comparison method. A comparison method is a query method that compares two objects and returns a value
that tells you which object is “greater” or “lesser” than the other one according to an ordering criterion. The
most well-known example is “boolean equals(Object)” to which Name adds the “boolean isEqual(Name)”
method.1 Some comparison methods are boolean query methods, but not all are necessarily so. It is a frequent
idiom to return an integer in the range “-1..1” to indicate that an object is less, equal, or greater than another
object.
• Conversion method. A conversion method is a query method that returns an object that represents the object
being queried using some other (typically simpler) object. The most well-known example is “String toString()” to
which Name adds the “String asString()” and “String asStringWith(char d)” methods. The “asStringWith”
method represents the name object with the d character as the delimiting character for name components.
You may know these method types under some other name. For example, conversion methods are also known as
converter or interpretation methods. The appended catalog lists the aliases I know.
1
It is important to be precise about the meaning of equals and isEqual. Depending on the task at hand, checking
for equality may provide different results. Object implements “equals” as an identity check. Specific subclasses,
for example Vector, do a deep comparison of two objects for field equality. For this to return “true”, the two
objects must be of the same class. Our “isEqual” method goes further and accepts instances of two different
classes, for example, StringName and VectorName, as equal if they have the same abstract field values.
The same argument applies to the “toString” and “asString” methods. By definition, “toString” provides a string
representation of an object usable for debugging, while “asString” provides human-readable output for a GUI. It
would be confusing for clients to override the original implementation that is provided by Object.
5
Each method type comes with its own naming convention. Getters typically have a “get” prefix (or none at all)
followed by the field being asked for. Boolean query methods start with prefixes like “is”, “has”, or “may”, followed
by an indication of the flag being queried. Conversion methods start with “to” or “as” followed by the class name of
the object being used as the representation. The method type catalog appended to this article lists these
conventions.
import java.util.*;
import org.riehle.Name.*;
import org.riehle.Name.Util.*;
/**
* Public convenience constructor
*/
public VectorName() {
this(“”, DELIMITER_CHAR, ESCAPE_CHAR);
}
6
/**
* Public convenience constructor, expects formally correct string.
*/
public VectorName(String name) {
this(name, DELIMITER_CHAR, ESCAPE_CHAR);
}
/**
* Public constructor, expects formally correct string.
*/
public VectorName(String name, char delimiter, char escape) {
super();
initialize(name, delimiter, escape);
}
/**
* Initializes VectorName object.
* Expects name argument to be formally correct string with delimiter and escape
chars.
*/
protected void initialize(String name, char delimiter, char escape) {
fComponents= new Vector();
int length= name.length();
if (length != 0) {
for (IntPair ip= new IntPair(0, 0); ip.y<length; ip.y++) {
String component= StringHelper.nextString(name, delimiter, escape, ip);
fComponents.addElement(component);
}
}
}
...
Listing 4: The “initialize(String, char, char)” method of VectorName and its uses.
The “void initialize(String, char, char)” method is a protected method used to initialize a VectorName object from a set
of parameters. The first parameter is a string that contains all name components, properly separated by delimiter
chars. The second parameter is the delimiter char itself. In the string, regular occurrences of the delimiter char are
masked through an escape char, which is the third parameter.
For example, a name object for “java.lang.String” requires you to call initialize with the following parameters:
“java.lang.String”, ‘.’, ‘\’ (the escape char isn’t really needed in this specific case). You could also initialize the name
object with the following initialize parameters: “java#lang#String”, ‘#’, ‘\’. The general delimiter + escape char scheme
lets you input any type of string without running into problems with reserved chars.
The “initialize” method parses the name parameter according to the delimiter and escape chars and initializes the
name object accordingly. The algorithm in Listing 4 breaks up the name parameter into its name components and puts
them into a Vector. The “initialize” method is called directly or indirectly from each of the three constructors
“VectorName()”, “VectorName(String)”, and “VectorName(String, char, char)”. The first two constructors are
convenience constructors that assume default parameters for the “initialize” method.
Hence, we have a third type of method: initialization methods.
• Initialization method. An initialization method is a mutation method that sets some or all fields of an object to an
initial value. Initialization methods are typically protected methods in support of public constructors, but they
may also be opened up to special clients for reinitializing an existing object.
A field is initialized lazily (lazy initialization), if its initialization is deferred until it is first accessed. If this idiom is used
a lot, the main initialization methods tend to initialize only a few fields, but not all.
7
Initialization methods are typically prefixed with “init” or called “initialize”.
The “VectorName(Vector)” constructor creates a new Vector and asks the helper method “copy(Vector, Vector)” of
the VectorHelper class to copy the constructor parameter into the “fComponents” Vector. Such a task is a typical
duty of a helper method.
Another example is the static “String nextString(String name, char delimiter, char escape, IntPair ip)” method of the
StringHelper class hinted at in the initialize method of Listing 4. Its purpose is to parse the name parameter for the
next name component using the delimiter and escape chars, and to advance the parse position in the IntPair ip to
continue with the next name component when called next time.
Next to such general helper methods, there are two important types of helper methods that deserve special attention.
We already mentioned the factory method “NameEnumeration components()” from the Name interface.
• Factory method. A factory method is a helper method that creates an object and returns it to the client [3].
Factory methods are sometimes prefixed with “create”, “make”, or “new”, followed by the product name.
The second important type of helper methods is the assertion method type. To understand this type of method,
consider Listing 7 and 8.
public void remove(int index) throws InvalidIndexException {
assertIsValidIndex(index);
fComponents.removeElementAt(index);
}
8
Listing 7 shows how the “void remove(int i)” method of VectorName calls the “void assertIsValidIndex(int i)” method
to ensure that the index parameter i is in the range of valid indices. Only if this precondition is fulfilled, does the
remove method work properly. Otherwise, an exception is thrown back to the client that called the remove method.
The “assertIsValidIndex” method is an assertion method.
• Assertion method. An assertion method is a helper method that checks whether a certain condition holds. If the
condition holds, it returns silently. If it does not hold, an appropriate exception is thrown.
Assertion methods are part of the larger design-by-contract scheme of designing interfaces [4]. They are used to
ensure at runtime that preconditions and postconditions of methods and invariants of classes are maintained.
9
/**
* Gets name component.
* @methodtype get
*/
public String component(int index) throws InvalidIndexException;
/**
* Sets name component.
* @methodtype set
*/
public void component(int index, String comp) throws InvalidIndexException;
/**
* Returns a simple human readable description.
* @methodtype conversion
*/
public String asString();
/**
* Inserts a name component.
* @methodtype command
*/
public void insert(int index, String comp) throws InvalidIndexException;
/**
* Returns name component enumeration.
* @methodtype factory
*/
public NameEnumeration components();
...
In the follow-up article, to the annotations of Listing 9, we add method properties like “convenience method” or
“template method” that concisely document how a method is to be used and how it is implemented.
5 Summary
This article provides us with a vocabulary to more effectively talk about methods in Java interfaces and classes. It
provides the most common method types and gives them a precise definition. If you feel that it leaves out some key
method types, let me know. If you know further aliases for the names of the method types provided here, let me also
know. At “http://www.riehle.org/java-report/” you can find a growing catalog of these and other method types as
well as the source code of the examples.
10
6 Acknowledgments
I would like to thank my colleagues Dirk Bäumer, Daniel Megert, Wolf Siberski, and Hans Wegener for reading and
commenting on this article.
The method type names are taken from several different sources:
• Arnold and Gosling’s Java the Language [1],
• Kent Beck’s book Smalltalk Best Practice Patterns [2],
• Gang-of-four’s book Design Patterns [3],
and, most importantly, from common knowledge and use.
7 References
[1] Ken Arnold and James Gosling. Java, the Programming Language. Addison-Wesley, 1996.
[2] Kent Beck. Smalltalk Best Practice Patterns. Prentice-Hall, 1996.
[3] Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns. Addison-Wesley, 1995.
[4] Bertrand Meyer. Object-oriented Software Construction, 2nd Edition. Prentice-Hall, 1998.
[5] Dirk Riehle and Erica Dubach. “Working with Java Interfaces and Classes: How to Separate Interfaces from
Implementations.” Java Report 4, 7 (July 1999). Page 35pp.
[6] Dirk Riehle and Erica Dubach. “Working with Java Interfaces and Classes: How to Maximize Design and Code
Reuse in the Face of Inheritance.” Java Report 4, 10 (October 1999). Page 34pp.
11
Naming: After the prefix (if any), the name of the field being queried follows.
12
Also known as: Setter.
JDK example: void Thread::setPriority(int), void Vector::addElement(Object).
Name example: void Name::component(String).
Prefix: (If any:) set.
Naming: After the prefix (if any), the field being changed follows.
13
8.3.2 Assertion method
Definition: An assertion method is a helper method that checks whether a certain condition holds. If
the condition holds, it returns silently. If it does not hold, an appropriate exception is
thrown.
Also known as: –
JDK example: –
Name example: void Name::assertIsValidIndex(int) throws InvalidIndexException.
Prefixes: assert, check, test.
Naming: After the prefix, the condition being checked follows.
Comment: Assertion methods are used to assert invariants about an object, for example
preconditions upon method entry and post-conditions upon method completion. They
are part of the larger design-by-contract scheme [4].
14