The other day me and my friends were discussing ways to implement filters. The things we focussed on were :
- Pluggable – The design should enable developers to add or remove filters as plug-ins
- Sequence – The order in which filters are applied should be configurable
- Testing – If adding a new filter, the developer should only be able to write a test case for the new filter and be done with it
Finally we agreed upon what is described best by the following UML ( disclaimer: we are not UML Gods, but use uml just to convey the idea):
There should be an interface which exposes the filtering function, for example, the Filter interface above exposes the doFilter() function. This function takes a sequence of results as input.- There may be n implementations of the Filter interface, each providing – ideally – a unique filtering functionality.
- The class which performs filtering (in this case the FilterEnforcer class)
- should be aware of the Filter interface and not of any implementations of the same.
- The member variable filters is an Array or List of filters, thereby determining the sequence in which the filters will be applied.
- The function which applies the these filters to the result-set will simply iterate over the filters and invoke the doFilter() function of each filter.
This design is already a widely used one – and if I am not wrong – I have seen this being implemented somewhere in Tomcat and Spring-Framework codebase.
Advertisement