Manage Complexity with the Facade Pattern

Share this article

Design patterns are built to standardize solutions for common problems faced in software development. When we develop complex applications, we should allocate sufficient time for planning the design and structure of the app. When we do so, we have the chance to choose appropriate design patterns. But there can be situations where we use a design pattern without even knowing that we’re using one. Facade is a design pattern used in almost every web application, but often without knowing. The term “design pattern” creates a mental image of something complex and difficult to understand. Even though this can be true sometimes, the Facade pattern is simple to implementation. Let’s see what Facade is and what it does to help us write good code.

The Process of Borrowing a Book

Assume that we’re developing an application for a library management system. Borrowing and returning books are obviously the two most important tasks of such systems. But consider a typical implementation of the book borrowing process:
  • A user comes to the library and returns her borrowed books so she can borrow new ones.
  • The user must pay a fine for overdue books.
  • The user, or a member of the library staff, searches for a new book.
  • The availability of the book is verified.
  • If the steps above are successfully completed, the location of the book must be retrieved.
  • The user borrows the book.
  • The status of the book is marked as unavailable in the system.
The implementation of each task is contained in separate classes with their own interfaces. The following code illustrates how a system might let the user borrow a book by calling the necessary methods:
<?php
public class User
{
    public function borrowBook() {
        $bookManager = new Book_Manager();
        $bookManager->returnBooks();

        $bookPayments = new Book_Payments();
        if ($bookPayments->hasOverdueBooks()) {
            $bookPayments->payBookFines();
        }

        $bookLibrary = new Book_Library();
        $bookReservations = new Book_Reservations();

        $book = $bookLibrary->searchBooks();
        $isAvailable = $bookLibrary->isBookAvailable($book);
        $isReserved = $bookReservations->isBookReserved($book); 
        if ($isAvailable && !isReserved) {
            $bookLibrary->locateBook($book);

            $bookManager->borrowBook($book);
            $bookLibrary->updateBookAvailability($book, $status);
        }
    }
}
You can see the process of borrowing a book is actually a complex process! In this implementation, a user has to interact with four different classes and around ten methods to borrow a book. Assume that each bit of functionality is implemented as a separate screen in the application; can you imagine the effort required for borrowing three books with this system? And the borrower doesn’t need to know about functionality such as checking reservations and updating the status. We certainly have a problem with our implementation.

Implementing a Library Facade

We need to decouple the user from the complex workflow of the library and allow for a simplified interface exposing just the information directly related to a user – a facade. Let’s see the implementation of the library facade.
<?php
class Library_Facade
{
    public function returnBooks() {
        // previous implementation by calling necessary classes
    }

    public function borrowBooks() {
    }

    public function searchBooks() {
    }

    public function reserveBooks() {
    }
}
The user can borrow books by calling the borrowBook() method of the Library_Facade class as shown in the following example:
<?php
class User
{
    public function borrowBook() {
        $libraryFacade = new Library_Facade();
        $libraryFacade->borrowBook();
    }
}
With this facade-based implementation, the user only talks to the Library_Facade class and has no idea how the functionality is implemented beyond it. A user can directly request any feature from the facade and the facade is responsible for handling the complex process and returning the appropriate information. The Facade pattern adheres to the principle of least knowledge in which each unit should have minimal knowledge about the other units. Even though the low-level functionality is hidden from the user through the facade, the user can still request low-level classes directly when needed. Think about your own projects and where you might find situations where you’ve implemented the Facade pattern without even realizing it.

Facade Pattern Definition

Since we’ve identified the process and importance of implementing the Facade pattern, now it’s time to learn the definition of the pattern. The following is extracted from Wikipedia:
A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand, and test since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade allowing more flexibility in developing a system;
  • wrap a poorly designed collection of APIs with a single well-designed API.
Here’s a class diagram of our library example that identifies the components mentioned in the Facade pattern definition.

facade-01

Real World Implementations

In the previous sections we learned the theory behind the Facade pattern using a library system as an example. In the real world, facades can be much more complex than the implementation in our library scenario. Let’s review some implementations of the pattern in the context of real-world applications and libraries.

Opauth for Open Authentication

I recently wrote an article about a popular Open Authentication library called Opauth, and I suggest you read it if you haven’t already. Assume we’ve developed a professional social network site and we want our users to be able to use other popular sites such as Twitter, LinkedIn, and Facebook to authenticate. To complete the authentication process we use existing third-party libraries for accessing the networks’ services. Let’s look at some sample code for with a Twitter library for achieving the desired functionality.
<?php
$toauth = new TwitterOAuth('consumer key', 'consumer secret');

$request_token = $toauth->getRequestToken('http://exmaple.com/twitter_oauth.php');

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

if ($toauth->http_code == 200) {
    $url = $toauth->getAuthorizeURL($request_token['oauth_token']);
    header('Location: '. $url);
}
else {
    // Generate error
}
As you can see, we call a set of Twitter-specific library methods to implement the desired functionality. A similar approach would be necessary for both LinkedIn and Facebook. The process has already become complex. We’re not developing a Twitter, Facebook, or Linkedin application; we should just validate the credentials and authenticate the user. Our application shouldn’t be worried about the implementation of each of these services. We can solve this problem by using the Opauth library as a facade interface. First we need to specify the login URLs of the desired services in a common format to be identified by the Opauth plugin. Consider the following code for implementing the authentication process.
<?php
public function login($stratergy = '') {
    if ($stratergy != '') {
        $this->opauth_lib->initialize();
    }
}
Once the login link is requested, Opauth identifies the requested service from the URL and initializes the library to redirect the user for authentication. Our application now only needs to create the login links and call the initialize method. All of the complex authentication stuff is handled behind-the-scenes using the respective libraries for each service. This can be considered a perfect example for effectively using the Facade pattern.

WordPress Meta Functions

WordPress is not one of the most popular frameworks among serious PHP developers considering the quality of its code. But we can easily find a number of successful facade implementations inside the WordPress codebase. Here I’ll take a look at the update_post_meta() function for saving custom data for WordPress posts. WordPress allows us to create custom fields associated with existing posts. Think of how we save these fields in a usual situation… we have to implement all the following tasks:
  • Validate the field data
  • Filter the data for HTML tags, scripts, and SQL injections
  • Check the existence of the field in database
  • Save or update the record based on the existence status
That’s quite a lot of work to save one single custom field! WordPress hides the complexity of saving these fields by providing a built-in function called update_post_meta() to act as a facade. This permits us to focus on passing the necessary data related to our application; all of the aforementioned tasks are hidden from the user. Now consider the implementation of update_post_meta()
to identify its functionality as a facade:
<?php
function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
    // make sure meta is added to the post, not a revision
    if ($the_post = wp_is_post_revision($post_id))
        $post_id = $the_post;

    return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
}

function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
    // expected_slashed ($meta_key)
    $meta_key = stripslashes($meta_key);
    $passed_value = $meta_value;
    $meta_value = stripslashes_deep($meta_value);
    $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);

    $check = apply_filters("update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value);
    if (null !== $check)
        return (bool) $check;

    // Compare existing value to new value if no prev value given and the key exists only once.
    if (empty($prev_value)) {
        $old_value = get_metadata($meta_type, $object_id, $meta_key);
        if (count($old_value) == 1) {
            if ($old_value[0] === $meta_value)
                return false;
        }
    }

    $wpdb->update($table, $data, $where);
}
Only the necessary code is shown; the complete source code for the update_metadata() function is available in meta.php file inside the wp-includes directory. But you can see all of the validation, filtering, and database updates are implemented here and only the facade interface has knowledge about the details.

Conclusion

Facade is one of the most simple and easy to use design patterns in software development. Throughout this article I talked about various implementations of the Facade pattern. Now it’s time to share your experiences in the comments below. Do you know of any library or service that makes use of facades? Feel free to share the practical implementations of the Facade pattern you’ve come across. Image via Fotolia

Frequently Asked Questions about the Facade Pattern

What is the main purpose of the Facade Pattern in software design?

The Facade Pattern is a structural design pattern that provides a simplified interface to a complex system of classes, library or framework. It hides the complexities of the system and provides an interface to the client from where the client can access the system. This pattern involves a single class which provides simplified methods required by the client and delegates calls to methods of existing system classes.

How does the Facade Pattern improve code readability and usability?

The Facade Pattern improves code readability and usability by providing a simple interface to a complex subsystem. Instead of making the client deal with several subsystem classes directly, the facade encapsulates the subsystems with a unified interface. This reduces the learning curve necessary to understand the subsystem and makes the subsystem easier to use and manage.

Can you provide a real-world example of the Facade Pattern?

A real-world example of the Facade Pattern is the use of a computer. When you turn on your computer, you don’t need to understand how the internal components work together to boot up the system. You simply press the power button (the facade) and the complex process happens behind the scenes.

What are the advantages and disadvantages of using the Facade Pattern?

The main advantage of the Facade Pattern is that it simplifies the interface to a complex subsystem, making it easier for the client to use. It also promotes decoupling between subsystems and their clients, which can make the system more modular and easier to maintain. However, a potential disadvantage is that the Facade Pattern can become a bottleneck if too much functionality is put into the facade. It can also hide useful features of the subsystem from the client.

How does the Facade Pattern differ from other structural design patterns?

Unlike other structural design patterns like the Adapter or Decorator patterns, which are used to add or change the behavior of individual objects, the Facade Pattern is used to simplify a complex system of classes. It provides a simplified interface to a complex subsystem, hiding the intricacies of the subsystem from the client.

Can the Facade Pattern be used with other design patterns?

Yes, the Facade Pattern can be used in conjunction with other design patterns. For example, it can be used with the Singleton Pattern to ensure that only one instance of the facade is created. It can also be used with the Abstract Factory Pattern to provide a simple interface to create families of related objects.

How does the Facade Pattern contribute to the principle of least knowledge?

The Facade Pattern contributes to the principle of least knowledge (or Law of Demeter) by limiting the communication between objects. The client only needs to communicate with the facade, not with the subsystem classes. This reduces the dependencies between objects, making the system more robust and easier to maintain.

Can the Facade Pattern be used in multi-threaded applications?

Yes, the Facade Pattern can be used in multi-threaded applications. However, care must be taken to ensure that the facade is thread-safe. This can be achieved by using synchronization mechanisms like locks or semaphores to prevent race conditions.

How does the Facade Pattern affect performance?

The Facade Pattern can improve performance by reducing the number of objects that the client needs to interact with. This can reduce the overhead of object creation and method invocation. However, if the facade becomes a bottleneck, it can negatively impact performance.

How can I implement the Facade Pattern in PHP?

To implement the Facade Pattern in PHP, you need to create a facade class that provides a simplified interface to the complex subsystem. The facade class should encapsulate the subsystem and delegate calls to the subsystem classes. The client should interact with the subsystem through the facade, not directly with the subsystem classes.

Rakhitha NimeshRakhitha Nimesh
View Author

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.

Advanced
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week