Always Programming to an interface.

With Java, Programming to an interface is often useful and a very common design pattern.  It can make it easier to change code and create different implementations in the future, minimizing impacts to a current implementation.  From my experience though, programming to an interface just to program to an interface is overkill, overkill, overkill.  A project I recently started working on uses interfaces for many objects in the system including JPA objects.

When using JPA it’s quite common for one object to contain a collection of another object. This composition is key to having an easy to work with data model.  However JPA does not specifically care bout implementing interfaces. in fact JPA annotations should not be used on interfaces. Having all of your JPA model objects programmed to an interface can be a little tricky to deal with.

Note the setter for hammers in WorkerImpl.java. We have to check the type of one of the elements in the list to see if the Cast is safe to do.

We want to make the list of hammers accessible to all of the child classes of Worker, and we must override this method since it exists in the parent class. For example, we want to program an adapter to convert some child class of worker into an xml bean to pass into a form. We don’t necessarily care about the implementation of of the hammer or the worker who owns them, perhaps we have many different implementations of one or both of these. We do however need access to the description of the hammer for whatever type of worker that gets passed into the method. The code above will allow us to parse through the list of hammers for a worker and pull the description.




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *