One of the anti-patterns that I encounter quite recently in the „enterprise” Java world is a one that I call the „Spring context template”. The motivation behind it is to enable code reuse and modularization. Unfortunately most of the time it creates more problems that it solves.
How does this pattern emerge ?
- there is some code that has a potential for reuse – e.g. common boilerplate for a server
- the wiring for that code is done via Spring XML context
- to allow reuse, the code is extracted along with the Spring XML context into a separate module/library
- there are extension points left in the XML context to supply your own implementation for some beans
- in order to use that module/library you have to import it’s main context XML and declare beans with expected id’s
What are the problems with the approach above:
- namespace pollution – hard to guess if any of our application beans clash with the ones declared by the lib
- no easy way to identify all extension points
- usually the lib has a few context XML files that may depend on each other, it makes it harder to replace a part of the default implementation
- these kinds of libs tend to be stacked one after another which makes the whole thing even more complex
Usually the problems with that kind of design are easily solved by a proper use of encapsulation:
- a library might be morphed into a service/microservice
- we might use the builder or factory pattern to hide implementation details and provide well documented extension points