Design patterns are often over glorified (especially if you live in the Java world), but they have their merits and knowing some of them can greatly help you sometimes. For example: from times to times you will certainly have to deal with that old, dated, blasphemous, legacy code and also with those poorly designed external libraries. Sometimes you just have have to use the APIs of those problematic codebases for small periods of time; in these you can safely ignore the ugliness and later forget you ever saw that atrocious 10 parameters method. But in other times you will be forced to wallow on that code for time enough to slowly lose your soul, and worse, for some reason you could even not be allowed to refactor the damn thing. It is in that kind of sad situations where we find very appropriate use cases for two interesting Design Patterns: the Facade and the Fluent Interface.
The Facade pattern
The Facade is one of my favorite patterns, it’s simply and powerful. With it you can take a complex API or set of APIs and wrap them in a new one that still exposes the original functionalities, but in a way that’s easier to use and understand.
Probably the most famous example is the jQuery library, it hides verbose DOM methods like
document.getElementById('id').getAttribute('attribute') and the
API, presenting instead simplified
$('#id').attr('attribute') and the
To give a more personal example: in my current work I develop web applications using an in-house built PHP framework, and it’s full of badly designed legacy code that cannot be refactored because that would break compatibility with older projects that still rely on framework updates. One of the most problematic parts of the framework is its module for abstracting the database DDL layer (the one responsible for creating tables and constraints), it’s something like this:
Besides doing what the names imply, the methods also do a lot of internal black magic to enforce the peculiar structure that the framework demands from the database. I’m not going to explain this structure because it wouldn’t be relevant to this post, let’s just say that the methods contains non trivial code and that rewrite the class from scratch isn’t a viable option.
Now let’s say you want to create some database schema for a question and answer website, for that you could use the following simplified structure:
- a table ‘question’ that has a ‘title’ and a ‘description’ column
- a table ‘answer’ for multiple possible answers for a question, it could have the columns ‘title’ and ‘description’ and a relation Nx1 with the table ‘question’ (a Foreign Key field)
- a table ‘comment’ with a ‘description’ column and a relation Nx1 with both ‘question’ and ‘answer’
Using the framework API we end up with the following:
At a first glance we can easily spot the problems with this code:
$retval = ...;
assertError($retval);calls are highly repetitive;
- calls to
falseto the two inner control parameters that I haven’t explained before. The thing is, those parameters control some internal behavior of the framework and are relevant, but in 99.9% percent of the use cases they should be
false, so they coming before the $cardinality parameter and thus not having default values end up being just an annoyance.
Now enters the Facade. In order to provide a more pleasant and concise API we could wrap the old class in a new one that
removes the redundancies and also the unnecessary parameters. First of, we can get rid of the
it’s obvious that every method should throw and exception if things go wrong, so it’s just a matter of moving
the exception throwing to their inside, child’s stuff. Them we can get rid of the
$innerControlParameters, if most
of the time they are false let’s put them a
false default value, trivial.
With those two simple observations we have this new “Facade” for the original API:
With that the database creation code would become:
As you can see the Facade provided a shorter and less noisy interface (and if you are as much of a fan of clean code as me this is something really important) without touching the original code.
Still, looking at this new code it looks like there is some verbosity left, every table name is used in the table
creation that happens with
createTable and also in the
maybe we could remove the need for those repetitions.
The Fluent Interface pattern
This pattern closely resembles the Facade because it also wraps some underlying API (or set of APIs) aiming to expose better ones, the difference is that it’s more concerned about the semantics of the API, this basically means that the pattern tries to present a more readable way to describe sets of actions. In OO this is usually done by allowing chaining of method calls in a way that the last method provides the context for the next. You can find a more detailed explanation of the pattern in this Martin fowler post, who as far as I know, is the guy who coined the “FluentInterface” term.
As an example of the pattern, lets get back to to that database layer improved with the Facade.
Although the new interface is much better than the original, a small redundancy concerning the multiple references to
the table name remained. To get rid of that we can leverage the power of the Fluent Interface providing context
through chaining. Instead of making a call to
then making calls to
createRelation(..., $tableName) we could provide the the
table context in the return of its creation, and then use this context in the
createColumn and createRelation calls. This can be accomplished with something like that:
Here’s a textual explanation of what was done:
- The new
creatTablemethod is static, it will create the table and return an instance of the
FluentDbFacadeclass, this instance will have the created table as a context (the
- The constructor of the class defines the context (the table that we are dealing with)
withColumnis a method of a
FluentDbFacadeinstance, it will create a column for the table that is in the current context
withRelationis also a method of a
FluentDbFacadeinstance, and it will create a relation (Foreign Key) from the context table to the other table specified as a parameter
With that we can refactor the code for the question and answer website structure to the following:
Nice! The new code is very terse and highly self-described, you can almost read it like regular english text: “Create a table question with a column called description that has the string type; create a table answer…”
The presented examples were very simple, but I hope that you can see the potential that facades and fluent interfaces have. You can surely find more complex use cases where they would be a nice fit for an API improvement.