Algorithms can be Static Methods
Algorithms can often be implemented by static methods, and this is especially useful when many different classes implement the same interface. Defining the algorithm's methods in each of those classes would be tedious, and would also violate the principle of Don't Repeat Yourself.
Consider, for example, an algorithm for sorting lists.
Java's standard libraries define at least 10 classes
that implement the List
interface,
and application programs often define still more classes
that implement List
.
Defining a separate sort method in all of those classes
would be silly.
Inheritance wouldn't solve the problem either, because
requiring every class that implements List
to inherit from one common superclass would interfere
with the use of inheritance to accomplish other goals.
List sorting algorithms should be representation independent:
They should work with any class that implements the
List
interface.
That means we should be able to define a static sort
method that works with any List
.
We don't have to do that ourselves, because Java's
standard libraries have already done that for us.
The java.util.Collections
class
consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
In Java, the List
interface extends the
Collection
interface, so every List
is also a Collection
.
It is considered good programming practice to define the
representation-independent static methods that operate on
all values of some interface type in a single class
whose name is the plural of the name of the interface.
Collections
, for example is the class that
defines static methods that operate on or return
a Collection
.
For our UTC
example, therefore, we should
consider defining a UTCs
class that contains
static methods that operate on values of the UTC
abstract data type.