Friday, October 5, 2007

Common code and the open closed policy




Common Application

Often a group of applications write the same code to perform a particular task such as looking up user information or looking up EJB services through a service locator, or executing a query after fetching a connection to the database. These common services can be made available using EJB or POJO objects.
It is often a good idea to write a separate application that handles all the common functionality for you. The application would have to be designed well enough to allow you to work with existing logic without having to change it every time the common application undergoes a change. The common application services can be accessed via EJB, Spring POJO, or simple POJO distributed through JAR files. The JAR file becomes part of the library for other applications to use.

Imagine that you have changed this common application and that the JAR file has to be updated in 20 other applications that use this common application. It would be cumbersome to test each application that uses the common services every time a change is made. Running a series of JUNIT tests is acceptable but manually testing the application every time a change is made is not.

Code that is written using the open-closed principle will not need such exhaustive testing. When you write code always make sure that your existing functionality is wrapped nicely and is robust so that you need not touch it at any point in time. Also reduce the number of methods that you need to invoke in a common library to satisfy a particular service. Whatever your services do internally should not be exposed to the outside world. When you write code to this formula, your code is open for enhancements to it yet closed to change any existing code that works for you. All existing code should be frozen for change and extra features should be add ons to the existing code without changing them in any way.

More on the open closed principle and other patterns/principles in this book, which I would highly recommend - Head first design patterns


No comments: