Java Idioms for Good and Evil

Over time programmers learn particular tricks in their programming languages and make some habits. Here is something from my Java collection.

Good Things

Assignment Result

Assignment expression has a result, but many people ignore it. You may use it to improve the code. Consider this example:

class Controller {

  private View view;

  public void setView(View view) {
    this.view = view;
    hookView(view);
  }

  protected void hookView(View view) {...}
}

Method setView() may be written in one line:

public void setView(View view) {
    hookView(this.view = view);
}

The positive effect of this change is not only that you have to type fewer characters. Now you have to read less and so can understand the code faster.

Method Chaining

This idiom is typically used on a library basis. The author of the library that is aware of this idiom designs library API in a way that allows method chaining. In practice this means that instead of returning void you should return this. Here is a conventional code:

  Composite plate = //...
  plate.add(label);
  plate.add(text);
  plate.add(button);

If add() method returns this, and in this case it is a plate, then calls to it could be chained:

  Composite plate = //...
  plate.add(label).add(text).add(button);

The benefits are again less text to type and less code to read.

Map Literal

This is a convenient way to create a one-off map. You fill the map in static initializer:

Collections.unmodifiableMap(new HashMap() {{
  this.put("key1", "value1");
  this.put("key2", "value2");
}});

Commando Pattern

Imagine that you are writing a unit test and have to check value of some private attribute, like currentPosition in java.util.StringTokenizer. But there is no accessor so you can't do it! Here comes a reflection-based hack that penetrates private defense like commando:

StringTokenizer st = //...
Integer currentPosition = null;
try {
  Field f = st.getClass().getDeclaredField("currentPosition");
  f.setAccessible(true);
  currentPosition = (Integer) f.get(st);
} catch (NoSuchFieldException nsfe) {
} catch (IllegalAccessException iae) {
}

Bad Things

'I' In Interface Names

I believe this convention came from C++ since there was no explicit notion of interface and people have to use abstract classes. Prepending their names with 'I' was the way to reassure others that such classes are indeed interfaces. There is no need to do this in Java. Moreover, interfaces should be as clean as possible by definition since they represent API and those 'I's are just noise that makes API harder to comprehend.

So if you a young programmer and prepend 'I's then others may think that you are blindly mimic bad habits. If you are a seasoned programmer then others may think that you are just too old.

False Instanceof

The normal way to check that an object is not an instance of a class is to negate instanceof operator. Some people are frustrated that negation has a higher priority and they have to use parenthesis:

if (!(obj instanceof String)) {
  // ...
}

So they write this check like this:

if (false == obj instanceof String) {
  // ...
}

The problem is not only that it's longer now but it's harder to read. The normal version reads like 'if not obj instance of string' and is close to english prose while the second version is quite far from it.

The counter argument is that the second version is easier to type: you don't have to press Shift key. It is true, but typically we write code once and read it several times later so I would prefer more readable version.

  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • LinkedIn
  • E-mail this story to a friend!
  • Print this article!

  • http://twitter.com/sarimarton Márton Sári

    "but typically we write code once and read it several times later so I would prefer more readable version"

    I consider this argument as erroneous. I think the psichological effort to read out something is highly connected with the effort to create that thing. This is due to our empathic nature. Furthermore, reading out many signs in a row is harder that reading out words. Parentheses grow the visual complexity of the code, it's hard to resolve their scope.

blog comments powered by Disqus