Java Tip #3: Shorter code with static factory methods

Java code can look much cleaner and shorter when using static factory methods combined with import static. These are methods, which return a new (or reused) instance of a class. Let’s say we have a HashMap which should use instances of KeyClass for the keys and a tuple of ValueClass1 and ValueClass2 as its values. Instead of writing lengthy code like

HashMap<KeyClass, Tuple<ValueClass1, ValueClass2>>
  myMap = new HashMap<KeyClass,
      Tuple2<ValueClass1, ValueClass2>>();

you could just use

HashMap<KeyClass, Tuple<ValueClass1, ValueClass2>>
  myMap = map();

Therefor, we need to create a static factory method named map somewhere with the following code:

public static <T1, T2> HashMap<T1, T2> map()
{
  return new HashMap<T1, T2>();
}

And then, when filling the HashMap, you can again make use of factory methods. Compared to

myMap.put(myKey,
  new Tuple2<ValueClass1, ValueClass2>(
    value1, value2));

the following code is much shorter:

myMap.put(myKey, t(value1, value2));

Nice, how easy tuples (or triples, or quadrupels, …) can be created in Java! Remember, that import static is needed to make it really short. We do not want to write Tuple.t(...) everywhere where we instantiate a tuple, but really only t(...). This is nearly as short as in the programming languages which support tuples natively.

One other example, where we always use those methods, are fractions. Instead of new Fraction(1, 4); we always use fr(1, 4). Actually we made the constructor private, so that programmers must use the factory method. This leads to much cleaner code. One real example from Zong!: Instead of

new Chord(new Note(new Pitch(1, 0, 4)),
  new Fraction(1, 4))

we just have to write

chord(note(pi(1, 0, 4)), fr(1, 4))

Downloads: Fraction, Tuple2, Tuple3

One thought on “Java Tip #3: Shorter code with static factory methods

  1. Pingback: Java Tip #5: Shorter singleton calls « The Zong! Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.