Showing posts with label design-patterns. Show all posts
Showing posts with label design-patterns. Show all posts

Monday, December 28, 2015

Coding to Interface

One of the nicest things you can add to your programming skills is coding to interface. One of the five principles of S.O.L.I.D is Dependency inversion principle which states:

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:1

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.

Pretty formal definition hun ? let's understand through example actually.

Imagine we have rudimentary MySQL wrapper class:

class Mysql
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this->db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

Pretty common and valid code in old days we used to be proud while writing such class. There are couple of problems associated with it though:

  • The class Mysql has implicit dependency (tight-coupling) on the PDO class. All dependencies should always be explicit not implicit.
  • It is hard to unit-test due to implicit dependency

Let's use above class:

class User
{
    private $database = null;

    public function __construct()
    {
        $this->database = new Mysql();
        $this->database->connect('mysql:host=localhost;dbname=test', 'root', '');
    }

    public function getUsers()
    {
        $users = $this->database->query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}

$user = new User();
$user->getUsers();

Again pretty common piece of code but again this one has even more problems:

  • The class User has implicit dependency (tight-coupling) on the Mysql class. All dependencies should always be explicit not implicit.
  • It is hard to unit-test due to implicit dependency
  • If we wanted to change database credentials, we need to edit the User class which is not good; every class should be completely modular or black box. If we need to operate further on it, we should actually use its public properties and methods instead of editing it again and again.
  • Let's assume right now class is using MySQL as database. What if we wanted to use some other type of database ? You will have to modify class.
  • The User class does not necessarily need to know about database connection, it should be confined to its own functionality only. So writing database connection code in User class doesn't make it modular. This defeats the Single responsibility principle.

You might wonder above code has problems but these days we write code based on MVC design pattern and follow best practices and write modern code but I am sure below code is pretty common even today using any framework you use:

class UserController extends Controller
{
    public function actionListAllUsers()
    {          
       // fetch all users from database
        $users = User::model()->findAll();

       // show them on screen
        print_r($users);          
    }
}

If you analyze this has same problems again in that class UserController is tightly coupled (implicit dependency) with User model class which also makes it hard to unit-test.

This means:

Coupled Code is Evil BIG DOT

So what's the solution ?

The solution is Dependency Injection (see my previous post Dependency Injection in PHP). The idea behind Dependency Injection is that instead of writing implicit dependencies, we should pass/provide those via constructor or setter method or even interface.

Let's refactor User class code and pass our dependency via constructor instead of hard-coding it inside User class method:

class User
{
    private $database = null;

    public function __construct(Mysql $database)
    {
        $this->database = $database;
    }

    public function getUsers()
    {
        $users = $this->database->query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}

$database = new Mysql();
$database->connect('mysql:host=localhost;dbname=test', 'root', '');
$user = new User($database);
$user->getUsers();

This is much better! We no more have implicit dependency on Mysql class which also makes our User class easier to unit-test. The class makes clear intention that it needs some sort of Mysql class. It also doesn't know (or care) where Mysql will come form, it just needs one to operate. The User class is now completely modular and follows single responsibility principle (that of manipulating users).

In the similar way, we can also improve our modern code:

class UserController extends Controller
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function actionListAllUsers()
    {          
       // fetch all users from database
        $users = $this->user->findAll();

       // show them on screen
        print_r($users);          
    }
}

Here again we pass dependency (User class) of UserController via its constructor making it much better. So all good ? Not really...

We still have a problem

One problem with User class which still persists is that it is tied to specific type of database (Mysql). What if we wanted to use some other database like Sqlite or SQL Server or some other ? Well this is where dependency inversion principle comes into play.

To overcome this problem, we need to create an interface (abstraction or contract - see definition of DIP above) which would allow us to use any database with User class. Here is our interface that all databases would implement:

interface DB
{
    public function connect($dsn, $user = '', $pass = '');
    public function query($query);
}

Here is Mysql class now implementing above interface:

class Mysql implements DB
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this->db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

Another database class implementing above interface:

class Sqlite implements DB
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this->db = new PDO($dsn);
    }

    public function query($query)
    {
        return $this->db->query($query);
    }
}

As you can see both Mysql and Sqlite implement methods imposed by the interface. Finally here is our User class:

class User
{
    private $database = null;

    public function __construct(DB $database)
    {
        $this->database = $database;
    }

    public function getUsers()
    {
        $users = $this->database->query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}

Notice that in constructor of above class, we are now passing interface rather than specific type of database.

Now we can use any database for the User class, here is example of Mysql:

$database = new Mysql();
$database->connect('mysql:host=localhost;dbname=test', 'root', '');
$user = new User($database);
$user->getUsers();

And example of Sqlite database class:

$database = new Sqlite();
$database->connect('sqlite:database.sqlite');
$user = new User($database);
$user->getUsers();

Amazing! we can now readily change database to be used with our User class, our User class is much more flexible by following the dependency inversion principle. If client requires to use some other database, no problem we implement one and specify to User class in similar fashion!

As you can see we took basic and common example of code and converted it into re-usable, flexible, modular and testable piece of code.

You might want to read more about S.O.L.I.D principles to write pleasant code and as bonus avoid S.T.U.P.I.D code.

Saturday, May 16, 2015

Singleton and Multiton Design Patterns

 

Singleton

One of the simplest design patterns is the Singleton. The purpose of Singleton design pattern is to always have a single instance of a some class. Singletons are usually used for things you don't necessarily need multiple instances of such as database or logging or similar. You always work with same instance of a singleton object.

This is how you create a singleton:

class MySingleton
{
    public static function getInstance()
    {
        static $instance;

        if (null === $instance) {
            $instance = new self();
        }

        return $instance;
    }

    // prevent creating multiple instances due to "private" constructor
    private function __construct(){}

    // prevent the instance from being cloned
    private function __clone(){}

    // prevent from being unserialized
    private function __wakeup(){}
}

Usage:

$instance = MySingleton::getInstance();

Following the same pattern, you can create your own singletons and add any necessary functionality you want. The main trick here is that we have made the constructor private which is what disallows creation of multiple instances of singleton class.

It is important to point out that Singleton design pattern is considered anti-pattern (and more so in the world of PHP) because of following reasons:

  • Singletons create global state which is bad; they create tight-coupling
  • Singletons are essentially class-oriented not object-oriented
  • We cannot tell what dependencies it contains, it hides logic
  • Because you cannot create multiple instances, you cannot easily test them
  • PHP runs on shared nothing architecture which essentially means unlike other languages like Java/.Net, life of a PHP application is just one http request which is why singletons do not make much sense in PHP

Having said that, many argue that you can at least use singletons for single-nature things like an instance of database or logging (though it is matter of personal preference on how you design database or logging stuff) while others avoid singletons completely (especially TDD Worshipers).

That's all there is to a singleton.

Multiton

As the name suggests, a multiton is a design pattern that helps you create multiple instances of itself. Both singleton and multiton are same, the only difference is that a multiton can store and retrieve multiple instances of itself. Obviously multiton suffers from same problems as singletons.

Here is example of multiton:

class Logger
{
    private static $instances = array();

    public static function getInstance($key)
    {
        if(!array_key_exists($key, self::$instances)) {
            self::$instances[$key] = new self();
        }

        return self::$instances[$key];
    }

    // prevent creating multiple instances due to "private" constructor
    private function __construct(){}

    // prevent the instance from being cloned
    private function __clone(){}

    // prevent from being unserialized
    private function __wakeup(){}
}

Usage:

$firstInstance = Logger::getInstance('file');
$secondInstance = Logger::getInstance('email');


Friday, May 15, 2015

Factory Design Pattern

 

Overview

Factory design pattern works like a factory in the real world in that it creates something for others to use. In the context of OOP, it helps in creating and instantiating objects.

Example

Let's say for our application we are using different types of databases based on requirement such as MySQL, PostgreSQL, and SQLite. Our classes look like this:

MySQL:

class MySQLDB
{
    public function setHost($host)
    {
        // code
    }
    public function setDB($db)
    {
        // code
    }
    public function setUserName($user)
    {
        // code
    }
    public function setPassword($pwd)
    {
        // code
    }
    public function connect()
    {
        // code
    }
}

PostgreSQL:

class PostgreSQLDB
{
    public function setHost($host)
    {
        // code
    }
    public function setDB($db)
    {
        // code
    }
    public function setUserName($user)
    {
        // code
    }
    public function setPassword($pwd)
    {
        // code
    }
    public function connect()
    {
        // code
    }
}

...and so on for SQLite database.

Then we instantiate different objects based on configuration:

if (Config::item('db_type') === 'mysql') {
    $DB = new MySQLDB();
    $DB->setHost("host");
    $DB->setDB("db");
    $DB->setUserName("user");
    $DB->setPassword("pwd");
    $DB->connect();
}
elseif (Config::item('db_type') === 'postgre') {
    $DB = new PostgreSQLDB();
    $DB->setHost("host");
    $DB->setDB("db");
    $DB->setUserName("user");
    $DB->setPassword("pwd");
    $DB->connect();
}
elseif (Config::item('db_type') === 'sqlite') {
    $DB = new SQLiteDB();
    $DB->setHost("host");
    $DB->setDB("db");
    $DB->setUserName("user");
    $DB->setPassword("pwd");
    $DB->connect();
}

Generally above works but it creates problems in rather big applications. Above code has these problems:

  • Should you add more database types, code would keep on growing making it complex
  • The code is hard coded with database type names
  • Whole process becomes tedious

To solve these issues, we can instead create a central factory object that would create those objects for us:

class DBFactory
{
    protected $driver = null;

    public function setDriver($driver)
    {
        $this->driver = $driver;
    }

    public function makeDB($host, $user, $pass, $dbname)
    {
        if ($this->driver === 'mysql') {
            $DB = new MySQLDB();
        }
        elseif ($this->driver === 'postgre') {
            $DB = new PostgreSQLDB();
        }
        elseif ($this->driver === 'sqlite') {
            $DB = new SQLiteDB();
        }

        $DB->setHost($host);
        $DB->setDB($dbname);
        $DB->setUserName($user);
        $DB->setPassword($pass);
        $DB->connect();

        return $DB;
    }
}

And then using it:

$dbFactory = new DBFactory;
$dbFactory->setDriver(Config::item('db_type'));
$DB = $dbFactory->makeDB("host", "db", "user", "pwd");

And that's it. You won't have to modify above code, it will always remain same, we have moved the complex object creation logic separate in the factory itself which now makes our code a lot more easier to work with.

Please notice that there are some variations of factory design pattern such as simple factory, abstract factory and factory method. In this example, we used the factory method eg we used a method named makeDB() to create our objects. Other variations are almost similar; for example with abstract factory, you actually create an abstract class and then all concrete classes should extend it. It just enforces commonality between similar concrete classes.

Note: In modern day, the object creation has become very simple with the help of Dependency Injection Containers and Service Locators. There are quite some DICs to choose from for PHP.


Monday, May 11, 2015

Adapter Design Pattern

 

Overview

The adapter design pattern as the name suggests is like real life adapter that converts one thing into some other one. Similarly, it can help us wrap functionality of some object into adapter providing us with consistent methods/API to work with. Understanding through an example is always the best way to learn.

Example

Suppose you have developed a website where client has asked you to allow users to post status updates on the Facebook. In order to to that, we use Facebook PHP client library which looks something like this:

class Facebook {    
    public function getUserToken($userId) {
        // code to get user token
    }

    public function postUpdate($message) {
        // code to post status update
    }
}

And then you use it to post updates on Facebook:

$statusUpdate = new Facebook;
$statusUpdate->getUserToken($someUserId);
$statusUpdate->postUpdate('some message');

Now let's assume suddenly client requires that instead of Facebook, he wants users to post updates on Twitter and Twitter's PHP client library looks like this:

class Twitter {    
    public function checkUserToken($userId) {
        // code to get user token
    }

    public function setStatusUpdate($message) {
        // code to post status update
    }
}

And here is the problem. We can see that Twitter's library has different method names which means we will have to modify code everywhere where we are using status updates. At this point, as developer, we should also not overrule the fact that client may again ask to use Facebook again or may be some other service to allow users to post status update but we don't want to change our code again and again.

So how do we make sure that:

  • We should be able to add any new service easily when client asks
  • We should be able to not modify code again and again, same code should post status updates without modifying it

This is where Adapter pattern comes out to be as life saver. In order to implement that, we first set rules/interface that all status update service should follow so let's create one:

interface iStatusUpdate {
    function getUserToken($userId);
    function postUpdate($message);
}

Now we create our Twitter adapter class:

class TwitterAdapter implements iStatusUpdate {

    protected $twitter;

    public function __construct(Twitter $twitter){
        $this->twitter = $twitter;
    }

    public function getUserToken($userId) {
        $this->twitter->checkUserToken($userId);
    }

    public function postUpdate($message) {
        $this->twitter->setStatusUpdate($message);
    }
}

Notice how we have passed Twitter object via the constructor. Of course we could have used setter or interface injection as well.

We can see that we now have same method names for Facebook and Twitter which means we won't have to modify much code in our codebase where we need to post status updates for users. Now all we need to do is to use our new adapter class providing it with actual Twitter object:

$statusUpdate = new TwitterAdapter(new Twitter);
$statusUpdate->getUserToken($someUserId);
$statusUpdate->postUpdate('some message');

As can be we have added a line or couple but most of status update code remains same, thanks to adapter pattern. We as developers should foresee such changes client may require in which case we would have created adapter class even for our first Facebook service and then we didn't need to modify even a single line of code.

Okay, client asks some other service to use, no problem:

class SomeOtherServiceAdapter implements iStatusUpdate {

    protected $otherService;

    public function __construct(SomeOtherService $otherService){
        $this->otherService = $otherService;
    }

    public function getUserToken($userId) {
        $this->otherService->authenticate($userId);
    }

    public function postUpdate($message) {
        $this->otherService->postMessage($message);
    }
}

And then:

$statusUpdate = new SomeOtherServiceAdapter(new SomeOtherService);
$statusUpdate->getUserToken($someUserId);
$statusUpdate->postUpdate('some message');

Again most of the code remains same.

So these simple examples show how useful and time-saver adapter pattern is. It provides us with consistent API to work with and allows us to use new services easily.


Popular Posts