Improve your Java: Restrict public methods to interface implementations

October 29, 2009

Good programming is all about restriction and constraint. Most possible programs do nothing interesting. Type systems, unit tests, code reviews and all that jazz are just ways of throwing out uninteresting programs.

Here is a chart view.

There are many more broken programs that good ones.

Notice the thickness of the blue slice.

This realization is what makes me feel comfortable proposing that we, as programmers, should mostly be thinking about new ways we can restrict ourselves.

Here is one way you can restrict your Java (or other classical Object-Oriented) programs to make them better.

Aran’s Public Interface Implementation Rule: All public methods on a class should be implementations of some explicit interface.

See, Java is tricky, because interfaces are interfaces, but so are classes. When you expose public methods on a class that are not part of an interface, a user of the method must specify the class name on the left hand side:

YourClassThatsAlsoAnInterface p = new YourClassThatsAlsoAnInterface();

That means their code is now glued to your implementation. They might not like that.

It would be better if you let them code to an interface and substitute implementations as desired. Thus, don’t bother putting public methods on a class that aren’t implementations of an interface.

YourInterface p = new yourClassThatsJustAClass();
YourInterface p2 = new theirReimplementationOfYourClassThatsJustAClass();

Incidentally, this rule totally enables Joshua Bloch’s Effective Java, Item 34: Refer to objects by their interfaces.

As Zak points out, the tradeoff is that you may hurt some compiler optimizations. If you have benchmarks to prove that following this rule causes unacceptable performance degradation, you have my permission to ignore it. Thanks for asking.

Leave your thoughts in the comments.


One Response to “Improve your Java: Restrict public methods to interface implementations”

  1. plagal Says:

    I agree. I’ve seen this happen with the code generated with EMF and it does look much more elegant.

Comments are closed.

%d bloggers like this: