Keep your implementations hidden

09 Oct, 2007
Xebia Background Header Wave

Most Java applications I have worked on the last years embraced the "Program to Interfaces" principle. The name is rather self explanatory so I won’t go into detail in the principle. As interfaces by itself are quite useless we need to have at least one implementation. In a typical application this is done by a defining a class such as:

public class JbcAddressDao implements AddressDao {

Nothing wrong here one might say, but I think that this code is in conflict with one of the main aspects of Object Orientation.

At QCON London 2006 Martin Fowler mentioned that one of the main aspects of OO is "Keeping secrets from each other". Since we defined the concrete implementation as public, the JdbcAddressDao is exposed to the outside world. There is nothing to prevent client code to use the implementation rather then the interface and therefor we loose our secret.
One way of dealing with this is that we could declare the constructor package private or protected. This will prevent client code from instantiating a JdbcAddressDao (in a real application the instantiation is probably done by a container like Spring which can handle package private and protected constructors), but the client code is still able to cast the interface to the concrete implementation. So this is a small improvement but still it exposes too much.
To really prevent client code to use a JdbcAddressDao we should declare it as package private. This way we are sure that no one outside our package can use our class. This does require that the implementation and interface are in the same package, which actually makes sense since implementation and interface are kind of related anyway. Containers like Spring can still instantiate package private classes and otherwise you could define a Factory to instantiate JdbcAddressDao and return it as a AddressDao.
I think when we are more careful in which access modifiers we use for implementations we are able to create more robust applications and are one step closer to OO heaven :-).


Get in touch with us to learn more about the subject and related solutions

Explore related posts