Monday, March 26, 2012

Use the Facade Pattern to avoid code duplication and to simplify source code navigation

I'm a big fan of having small concrete classes that does one thing. This allows for easy testing and easy maintenance. However in larger codebases this can also give us a challenge. Due to the large number of classes it can be hard to get an overview of all the available operations and this might lead to code duplication.
Luckily we have design patterns for the most common problems, and a nice pattern to use in this scenario is the Facade Pattern. By creating a facade class per feature/module we can make all the public operations available through a single class, then this will help us to get a better overview of the codebase and help us to avoid code duplication:

What is important to notice is that whenever a class needs to go outside its boundary then the Facade class for the requested feature must be called. For instance if the CustomerUpdater class needs to get the customer then this should be done through the CustomerFacade and not through the CustomerFetcher class, and if it needs to get the employee assigned to the customer then this should be done through the EmployeeFacade.