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 XMLHttpRequest API, presenting instead simplified versions like $('#id').attr('attribute') and the $.ajax method.

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:

<?php
class DbMeta {
    public function createTable($tableName) {
        ...
        return ['status' => boolean, 'message' => string]
    }

    public function createColumn($name, $type, $table) {
        ...
        return ['status' => boolean, 'message' => string]
    }

    /**
    * @param $innerControlParameter and $innerControlParameter2
    *    I'm going to explain those later
    * @param $cardinality string
    *    '1xN' $table1 has many $table2 ||
    *    'Nx1' $table2 has many $table1 ||
    *    'NxN'
    */
    public function createRelation(
        $table1, $table2,
        $innerControlParameter, $innerControlParameter2,
        $cardinality
    ) {
        ...
        return ['status' => boolean, 'message' => string]
    }
}

function assertError($retval) {
    if (!$retval['status']) {
        throws new Exception($retval['message']);
    }
}

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:

<?php
$dbMeta = new DbMeta();

$retval = $dbMeta->createTable('question');
assertError($retval);typeName
$retval = $dbMeta->createTable('answer');
assertError($retval);
$retval = $dbMeta->
    createColumn('description', 'string', 'answer');
assertError($retval);
$retval = $dbMeta->
    createRelation('question', 'answer', false, false, '1xN');
assertError($retval);

$retval = $dbMeta->createTable('comment');
assertError($retval);
$retval = $dbMeta->
    createColumn('description', 'string', 'comment');
assertError($retval);
$retval = $dbMeta->
    createRelation('comment', 'question', false, false, '1xN');
assertError($retval);
$retval = $dbMeta->
    createRelation('comment', 'answer', false, false, '1xN');
assertError($retval);

At a first glance we can easily spot the problems with this code:

  1. the $retval = ...; assertError($retval); calls are highly repetitive;
  2. calls to ->createRelation always pass false to 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 assertError function, 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:

<?php
class DbMetaFacade {
    public function createTable($tableName) {
        ...
        if (something went wrong) { throws new Exception($message); }
    }

    public function createColumn($name, $type, $table) {
        ...
        if (something went wrong) { throws new Exception($message); }
    }

    public function createRelation($table1, $table2, $cardinality) {
        ...
        if (something went wrong) { throws new Exception($message); }
    }
}

With that the database creation code would become:

<?php
$dbMeta = new DbMetaFacade();

$dbMeta->createTable('question');
$dbMeta->createColumn('description', 'string', 'question');

$dbMeta->createTable('answer');
$dbMeta->createColumn('description', 'string', 'answer');
$dbMeta->createRelation('question', 'answer' '1xN');

$dbMeta->createTable('comment');
$dbMeta->createColumn('description', 'string', 'comment');
$dbMeta->createRelation('comment', 'question' '1xN');
$retval = $dbMeta->createRelation('comment', 'answer', '1xN');

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 createColumn and createRelation calls, 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 createTable($tableName) then making calls to createColumn(..., $tableName), 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:

<?php
class FluentDbFacade {
    private $contextTable = null;

    static public function createTable($tableName) {
        ...
        if (something went wrong) { throws new Exception($message); }
        else {
            return new FluentDbFacade($tableName);
        }
    }

    public function __construct($tableName) {
        $this->contextTable = $tableName;
    }

    public function withColumn($name, $type) {
        // create a column in the table $this->contextTable
        ...
        if (something went wrong) { throws new Exception($message); }
        else { return $this; }
    }

    public function withRelation($table2, $cardinality) {
        // create a column in the table $this->contextTable
        ...
        if (something went wrong) { throws new Exception($message); }
        else { return $this; }
    }
}

Here’s a textual explanation of what was done:

  1. The new creatTable method is static, it will create the table and return an instance of the FluentDbFacade class, this instance will have the created table as a context (the contextTable attribute)
  2. The constructor of the class defines the context (the table that we are dealing with)
  3. withColumn is a method of a FluentDbFacade instance, it will create a column for the table that is in the current context
  4. withRelation is also a method of a FluentDbFacade instance, 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:

<?php
FluentDbFacade::createTable('question')
    ->withColumn('description', 'string');

FluentDbFacade::createTable('answer')
    ->withColumn('description', 'string')
    ->withRelation('question', '1xN');

FluentDbFacade::createTable('comment')
    ->withColumn('description', 'string')
    ->withRelation('question', '1xN')
    ->withRelation('answer', '1xN');

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.