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

  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

2 Responses to Java Tip #3: Shorter code with static factory methods

  1. […] this be shortened? Yes! Like in Java Tip #3, we can use public static methods and static import. But then, we do not see at a glance what […]

  2. says:

    The combat is king of thieves hacks shallow and repetitive.

    Also, I said Asian, but if they’re the creators of it.
    One of the original game didn’t have 3D graphics
    were starting to revamp their.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s