Archive for September 13th, 2006

Don’t Be Afraid of Procedural Java

Wednesday, September 13th, 2006

Consider this simple parsing class:

public class Parser {

  private String s;

  public Parser(String s) {
    this.s = s;
  }

  public Result parse() {
    ...
  }

  // other private methods
}

A typical usage might be:

String toParse = ...
Parser parser = new Parser(toParse);
Result result = parser.parse();

Since the instance is only used to call a single method and then discarded, we can rewrite as:

String toParse = ...
Result result = new Parser(toParse).parse();

Since the class doesn’t implement any interfaces and is unlikely to be subclassed – it’s a utility class – it’s pretty clear that there’s no need for the class to maintain state, and that there’s no need to be instantiable. The method(s) should be static:

String toParse = ...
Result result = Parser.parse(toParse);

Now this doesn’t feel like OO programming, and that’s fine. Object-oriented code is very appropriate for many tasks but sometimes you just need to call a global method.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.