Tags

Use minimal interface

March 23rd, 2006

Two things to notice:

Even a class that does not implement an interface has an interface! In fact the interface of a class is its collection of public methods (for extending classes you have to add also the protected methods and fields to it, and for package siblings even default visibilty).

The declaration “implements interface” is the merely the subset of methods you really want to be used (sometimes to have to make methods public for technical reasons, but these are implementation details)! That is the point behind programming against interfaces.

The declaration of an interface and the consequent use makes clear which methods should be called by the user of of class and which not.

If you don’t declare an interface you are missing this part of expressivity.

What about the title of this post? Sometime (in pre-Java5 code) you have to cast down. When use restrict yourself to to minimal interface that suits your job, you’ll make refactoring easier for the generations of programmers that have to deal with your code after you got happily(?) rid of it. OK, we should you care? Because sometime you get the benefit even yourself by having less ClassCastExceptions:

short sAshort = ((Short)getObject(col)).shortValue();

Well, if your getObject() decides to simply construct a Long for each integer value, your code will crash always. Downside: you won’t have the ClassCastExceptions anymore, so need something like

if (sAshort != ((Number)obj).intValue()) throw new NumberFormatException();

but this is a different story.

Unfortunately though Java made the concept of interfaces popular, it has some short-comings:

  1. When creating an anonymous class you can only implement a single interface or extend a class.
  2. A return type declares only a single-type, something like Readable,Writeable getAccessor() would be nice.
  3. In turn you should be able to declare parameters like setRWAccessor(Readable,Writeable accessor)

This would make the code much more clear because you’ll define less interfaces that just aggregate existing interfaces (normally one needs a lot of them, because you don’t want to violate the minimality principle again; also fewer casts would be needed.

One Response to “Use minimal interface”

  1. anjan bacchu Says:

    hi there,

    you can use dynamic proxies(http://java.sun.com/j2se/1.5.0/docs/guide/reflection/proxy.html) which give you anonymous classes that implement multiple interfaces.

    BR,
    ~A

Leave a Reply