Tagged: Python

Design Patterns: Bridge

Today I’m going to write some examples of Bridge. The design pattern not the game. Bridge is a structural pattern that decouples abstraction from the implementation of some component so the two can vary independently. The bridge pattern can also be thought of as two layers of abstraction[3].

Bridge pattern is useful in times when you need to switch between multiple implementations at runtime. Another great case for using bridge is when you need to couple pool of interfaces with a pool of implementations (e.g. 5 different interfaces for different clients and 3 different implementations for different platforms). You need to make sure, that there’s a solution for every type of client on each platform. This could lead to very large number of classes in the inheritance hierarchy doing virtually the same thing. The implementation of the abstraction is moved one step back and hidden behind another interface. This allows you to outsource the implementation into another (orthogonal) inheritance hierarchy behind another interface. The original inheritance tree uses implementation through the bridge interface. Let’s have a look at diagram in Figure 1.

Bridge pattern UML diagram

Figure1: Bridge pattern UML diagram

As you can see, there are two orthogonal inheritance hierarchies. The first one is behind ImplementationInterface. This implementation is injected using aggregation through Bridge class into the second hierarchy under the AbstractInterface. This allows having multiple cases coupled with multiple underlying implementations. The Client then uses objects through AbstractInterface. Let’s see it in code.

C++

/* Implemented interface. */
class AbstractInterface
{
    public:
        virtual void someFunctionality() = 0;
};

/* Interface for internal implementation that Bridge uses. */
class ImplementationInterface
{
    public:
        virtual void anotherFunctionality() = 0;
};

/* The Bridge */
class Bridge : public AbstractInterface
{
    protected:
        ImplementationInterface* implementation;

    public:
        Bridge(ImplementationInterface* backend)
        {
            implementation = backend;
        }
};

/* Different special cases of the interface. */

class UseCase1 : public Bridge
{
    public:
        UseCase1(ImplementationInterface* backend)
          : Bridge(backend)
        {}

        void someFunctionality()
        {
            std::cout << "UseCase1 on ";
            implementation->anotherFunctionality();
        }
};

class UseCase2 : public Bridge
{
    public:
        UseCase2(ImplementationInterface* backend)
          : Bridge(backend)
        {}

        void someFunctionality()
        {
            std::cout << "UseCase2 on ";
            implementation->anotherFunctionality();
        }
};

/* Different background implementations. */

class Windows : public ImplementationInterface
{
    public:
        void anotherFunctionality()
        {
            std::cout << "Windows" << std::endl;
        }
};

class Linux : public ImplementationInterface
{
    public:
        void anotherFunctionality()
        {
            std::cout << "Linux!" << std::endl;
        }
};

int main()
{
    AbstractInterface *useCase = 0;
    ImplementationInterface *osWindows = new Windows;
    ImplementationInterface *osLinux = new Linux;

    /* First case */
    useCase = new UseCase1(osWindows);
    useCase->someFunctionality();

    useCase = new UseCase1(osLinux);
    useCase->someFunctionality();

    /* Second case */
    useCase = new UseCase2(osWindows);
    useCase->someFunctionality();

    useCase = new UseCase2(osLinux);
    useCase->someFunctionality();

    return 0;
}

Download complete source file from github.

Python


class AbstractInterface:

    """ Target interface.

    This is the target interface, that clients use.
    """

    def someFunctionality(self):
        raise NotImplemented()

class Bridge(AbstractInterface):

    """ Bridge class.
    
    This class forms a bridge between the target
    interface and background implementation.
    """

    def __init__(self):
        self.__implementation = None

class UseCase1(Bridge):

    """ Variant of the target interface.

    This is a variant of the target Abstract interface.
    It can do something little differently and it can
    also use various background implementations through
    the bridge.
    """
    
    def __init__(self, implementation):
        self.__implementation = implementation

    def someFunctionality(self):
        print "UseCase1: ",
        self.__implementation.anotherFunctionality()

class UseCase2(Bridge):
    def __init__(self, implementation):
        self.__implementation = implementation

    def someFunctionality(self):
        print "UseCase2: ",
        self.__implementation.anotherFunctionality()

class ImplementationInterface:
    
    """ Interface for the background implementation.

    This class defines how the Bridge communicates
    with various background implementations.
    """

    def anotherFunctionality(self):
        raise NotImplemented

class Linux(ImplementationInterface):

    """ Concrete background implementation.

    A variant of background implementation, in this
    case for Linux!
    """

    def anotherFunctionality(self):
        print "Linux!"

class Windows(ImplementationInterface):
    def anotherFunctionality(self):
        print "Windows."

def main():
    linux = Linux()
    windows = Windows()

    # Couple of variants under a couple
    # of operating systems.
    useCase = UseCase1(linux)
    useCase.someFunctionality()

    useCase = UseCase1(windows)
    useCase.someFunctionality()

    useCase = UseCase2(linux)
    useCase.someFunctionality()

    useCase = UseCase2(windows)
    useCase.someFunctionality()

Download complete source file from github.

Summary

The Bridge pattern is very close to the Adapter by it’s structure, but there’s a huge difference in semantics. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together [1].

Sources

  1. http://sourcemaking.com/design_patterns/bridge
  2. http://www.oodesign.com/bridge-pattern.html
  3. http://en.wikipedia.org/wiki/Bridge_pattern

Design Patterns: Adapter

And back to design patterns! Today it’s time to start with structural patterns, since I have finished all the creational patterns. What are those structural patterns anyway?

In Software Engineering, Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities.

The first among the structural design patterns is Adapter. The name for it is totally appropriate, because it does exactly what any other real-life thing called adapter does. It converts some attribute of one device so it is usable together with another one. Most common adapters are between various types of electrical sockets. The adapters usually convert the voltage and/or the shape of the connector so you can plug-in different devices.

The software adapters work exactly like the outlet adapters. Imagine having (possibly a third-party) class or module you need to use in your application. It’s poorly coded and it would pollute your nicely designed code. But there’s no other way, you need it’s functionality and don’t have time to write it from scratch. The best practice is to write your own adapter and wrap the old code inside of it. Then you can use your own interface and therefore reduce your dependence on the old ugly code.

Especially, when the code comes from a third-party module you have no control on whatsoever. They could change something which would result in breaking your code on many places. That’s just unacceptable.

Adapter pattern example

UML example of adapter pattern

Here is an example class diagram of adapter use. You see there is some old interface which the adapter uses. On the other end, there is new target interface that the adapter implements. The client (i.e. your app) then uses the daisy fresh new interface. For more explanation see the source code examples bellow.

C++

typedef int Cable; // wire with electrons

/* Adaptee (source) interface */
class EuropeanSocketInterface
{
    public:
        virtual int voltage() = 0;

        virtual Cable live() = 0;
        virtual Cable neutral() = 0;
        virtual Cable earth() = 0;
};

/* Adaptee */
class Socket : public EuropeanSocketInterface
{
    public:
        int voltage() { return 230; }

        Cable live() { return 1; }
        Cable neutral() { return -1; }
        Cable earth() { return 0; }
};

/* Target interface */
class USASocketInterface
{
    public:
        virtual int voltage() = 0;

        virtual Cable live() = 0;
        virtual Cable neutral() = 0;
};

/* The Adapter */
class Adapter : public USASocketInterface
{
    EuropeanSocketInterface* socket;

    public:
        void plugIn(EuropeanSocketInterface* outlet)
        {
            socket = outlet;
        }

        int voltage() { return 110; }
        Cable live() { return socket->live(); }
        Cable neutral() { return socket->neutral(); }
};

/* Client */
class ElectricKettle
{
    USASocketInterface* power;

    public:
        void plugIn(USASocketInterface* supply)
        {
            power = supply;
        }

        void boil()
        {
            if (power->voltage() > 110)
            {
                std::cout << "Kettle is on fire!" << std::endl;
                return;
            }

            if (power->live() == 1 && power->neutral() == -1)
            {
                std::cout << "Coffee time!" << std::endl;
            }
        }
};

int main()
{
    Socket* socket = new Socket;
    Adapter* adapter = new Adapter;
    ElectricKettle* kettle = new ElectricKettle;

    /* Pluging in. */
    adapter->plugIn(socket);
    kettle->plugIn(adapter);

    /* Having coffee */
    kettle->boil();

    return 0;
}

Download example from Github.

Python

# Adaptee (source) interface
class EuropeanSocketInterface:
    def voltage(self): pass

    def live(self): pass
    def neutral(self): pass
    def earth(self): pass

# Adaptee
class Socket(EuropeanSocketInterface):
    def voltage(self):
        return 230

    def live(self):
        return 1

    def neutral(self):
        return -1

    def earth(self):
        return 0

# Target interface
class USASocketInterface:
    def voltage(self): pass

    def live(self): pass
    def neutral(self): pass

# The Adapter
class Adapter(USASocketInterface):
    __socket = None

    def __init__(self, socket):
        self.__socket = socket

    def voltage(self):
        return 110

    def live(self):
        return self.__socket.live()

    def neutral(self):
        return self.__socket.neutral()

# Client
class ElectricKettle:
    __power = None

    def __init__(self, power):
        self.__power = power

    def boil(self):
        if self.__power.voltage() > 110:
            print "Kettle on fire!"
        else:
            if self.__power.live() == 1 and \
               self.__power.neutral() == -1:
                print "Coffee time!"
            else:
                print "No power."

def main():
    # Plug in
    socket = Socket()
    adapter = Adapter(socket)
    kettle = ElectricKettle(adapter)

    # Make coffee
    kettle.boil()

    return 0

if __name__ == "__main__":
    main()

Download example from Github.

Summary

The adapter uses the old rusty interface of a class or a module and maps it’s functionality to a new interface that is used by the clients. It’s kind of wrapper for the crappy code so it doesn’t get your code dirty.

Sources

Design Patterns: Object Pool

Last one from the family of creational patterns is Object Pool. The main purpose of object pool and why designers choose to incorporate to the software is a performance boost. Construction and destruction of object can become very expensive operation in some cases (especially if it occurs very often). Constant building and throwing away instances may significantly slow down your application. Object Pool pattern offers a solution to this problem.

Object pool is a managed set of reusable objects. Clients then “check out” objects from the pool return them back when they don’t need them any more. But it’s not that easy as it sounds. The manager of the pool has to deal with various problems.

  • What happens if the pool is empty and a client asks for an object?
    Some implementations work with growing pool of objects. That means if there’s no object available at the time of the request the pool manager creates one more. The manager can also destroy objects periodically when they’re not used. But what was the initial goal? Performance boost? Well, with this amount of overhead it might not be as fast. Another solution to the problem is simply to decline a client’s request if the pool is empty. This also slows down your system, because clients needs to do things right now and not wait for someone else to free up resources.
  • When the reservation expires?
    The other problem is dealing with errors. Every client must explicitly free up the resource when he’s done. But programmers are also only humans (well, in most cases) and there will be errors and your pool can easily become a hole full of zombies. So you might need to implement an algorithm for detecting and freeing expired reservations on resources in order to make stuff work properly.
  • Synchronization in multi-threaded applications
    Multi-threading brings into the game a whole other aspect. Two processes asking for resources at the same time. Some synchronization tools might be necessary as well.

As you can see, there are some serious drawbacks in this pattern. It’s a huge amount of work in the first place, if you decide to implement all the above. You need to consider every aspect very carefully before you implement the object pool and evaluate whether it really is, what you need.

The resource manager can be implemented many ways. Static class or singleton will work. I personally chose singleton. Here is my implementation of object pool:

C++

/*
 * Example of `object pool' design pattern
 * Copyright (C) 2011 Radek Pazdera
 */

class Resource
{
    int value;

    public:
        Resource()
        {
            value = 0;
        }

        void reset()
        {
            value = 0;
        }

        int getValue()
        {
            return value;
        }

        void setValue(int number)
        {
            value = number;
        }
};

/* Note, that this class is a singleton. */
class ObjectPool
{
    private:
        std::list<Resource*> resources;
        
        static ObjectPool* instance;
        ObjectPool() {}

    public:
        /**
         * Static method for accessing class instance.
         * Part of Singleton design pattern.
         *
         * @return ObjectPool instance.
         */
        static ObjectPool* getInstance()
        {
            if (instance == 0)
            {
                instance = new ObjectPool;
            }
            return instance;
        }

        /**
         * Returns instance of Resource.
         * 
         * New resource will be created if all the resources
         * were used at the time of the request.
         *
         * @return Resource instance.
         */
        Resource* getResource()
        {
            if (resources.empty())
            {
                std::cout << "Creating new." << std::endl;
                return new Resource;
            }
            else
            {
                std::cout << "Reusing existing." << std::endl;
                Resource* resource = resources.front();
                resources.pop_front();
                return resource;
            }
        }

        /**
         * Return resource back to the pool.
         *
         * The resource must be initialized back to
         * the default settings before someone else
         * attempts to use it.
         *
         * @param object Resource instance.
         * @return void
         */
        void returnResource(Resource* object)
        {
            object->reset();
            resources.push_back(object);
        }
};

int main()
{
    ObjectPool* pool = ObjectPool::getInstance();
    Resource* one;
    Resource* two;

    /* Resources will be created. */
    one = pool->getResource();
    one->setValue(10);
    std::cout << "one = " << one->getValue() << " [" << one << "]" << std::endl;

    two = pool->getResource();
    two->setValue(20);
    std::cout << "two = " << two->getValue() << " [" << two << "]" << std::endl;

    pool->returnResource(one);
    pool->returnResource(two);

    /* Resources will be reused. 
     * Notice that the value of both resources were reset back to zero.
     */
    one = pool->getResource();
    std::cout << "one = " << one->getValue() << " [" << one << "]" << std::endl;

    two = pool->getResource();
    std::cout << "two = " << two->getValue() << " [" << two << "]" << std::endl;
   
    return 0;
}

Download the fully working example from github.

Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Example of `object pool' design pattern
# Copyright (C) 2011 Radek Pazdera

class Resource:

    """ Some resource, that clients need to use.
    
    The resources usualy have a very complex and expensive
    construction process, which is definitely not a case
    of this Resource class in my example.
    """

    __value = 0

    def reset(self):
        """ Put resource back into default setting. """
        self.__value = 0

    def setValue(self, number):
        self.__value = number

    def getValue(self):
        return self.__value


class ObjectPool:
    
    """ Resource manager.

    Handles checking out and returning resources from clients.
    It's a singleton class.
    """

    __instance = None
    __resources = list()

    def __init__(self):
        if ObjectPool.__instance != None:
            raise NotImplemented("This is a singleton class.")

    @staticmethod
    def getInstance():
        if ObjectPool.__instance == None:
            ObjectPool.__instance = ObjectPool()

        return ObjectPool.__instance

    def getResource(self):
        if len(self.__resources) > 0:
            print "Using existing resource."
            return self.__resources.pop(0)
        else:
            print "Creating new resource."
            return Resource()

    def returnResource(self, resource):
        resource.reset()
        self.__resources.append(resource)

def main():
    pool = ObjectPool.getInstance()

    # These will be created
    one = pool.getResource()
    two = pool.getResource()

    one.setValue(10)
    two.setValue(20)

    print "%s = %d" % (one, one.getValue())
    print "%s = %d" % (two, two.getValue())

    pool.returnResource(one)
    pool.returnResource(two)

    one = None
    two = None

    # These resources will be reused
    one = pool.getResource()
    two = pool.getResource()
    print "%s = %d" % (one, one.getValue())
    print "%s = %d" % (two, two.getValue())

Download the fully working example from github.

Sources

Design Patterns: Prototype

Prototype is one of the easier to understand design patterns. The intent of prototype is to create new instances of classes by cloning a prototype instance, rather than building them from scratch. This is particularly useful when the initialization of the objects is very expensive and very similar among the majority of created instances.

Take this for instance, you have some data stored on a remote server. You need them to initialize 1000 instances of some class during your program runtime. This data are static and very unlikely to be changed during the runtime of your application. You see, that downloading the data during initialization in constructor is pretty ineffective. Design like that would lead to exactly 999 pointless connections to the server and a lot of unnecessary network traffic, which is a gigantic waste of resources and time. If you use prototype instead, the application will download the data just once and the 1000 more instances will be cloned from the first one, saving us all the trouble.

There are three participants in the prototype pattern:

  • Client – creates a new object by asking a prototype to clone itself.
  • Prototype – declares an interface for cloning itself.
  • Concrete Prototype – implements the operation for cloning itself.

You also need a place where all the prototypes will be stored. A good practice is using a factory class that will cover the initial prototype setup  and will handle the cloning operations. This might remind you of the abstract factory design pattern. This is because they both are creational patterns and can be used to achieve the same behavior. The thing about prototype is that, you can dynamically change the prototype instance during the runtime and begin constructing something completely different with the same factory without sub-classing it.

Another way of dynamic handling a lot of prototype instances is prototype manager. A class that stores a pool of prototypes and makes decisions on which one to instantiate based on some parameters. This is particularly useful when the amount of prototypes isn’t fixed.

Now, let’s proceed to the code examples. I went with the first variant — a factory class for storing the prototypes.

C++

/*
* Example of `prototype' design pattern.
* Copyright (C) 2011 Radek Pazdera
*/

#include <iostream>
#include <string>

/* Prototype base class. */
class Prototype
{
    protected:
        std::string type;
        int value;

    public:
        virtual Prototype* clone() = 0;

        std::string getType()
        {
            return type;
        }

        int getValue()
        {
            return value;
        }
};

class ConcretePrototype1 : public Prototype
{
    public:
        ConcretePrototype1(int number)
        {
            type  = "Type1";
            value = number;
        }
        
        Prototype* clone()
        {
            return new ConcretePrototype1(*this);
        }
};

class ConcretePrototype2 : public Prototype
{
    public:
        ConcretePrototype2(int number)
        {
            type  = "Type2";
            value = number;
        }

        Prototype* clone()
        {
            return new ConcretePrototype2(*this);
        }
};

/* Factory that manages prorotype instances and produces their clones. */
class ObjectFactory
{
    static Prototype* type1value1;
    static Prototype* type1value2;
    static Prototype* type2value1;
    static Prototype* type2value2;

    public:
        static void  initialize()
        {
            type1value1 = new ConcretePrototype1(1);
            type2value1 = new ConcretePrototype2(1);
        }

        static Prototype* getType1Value1()
        {
            return type1value1->clone();
        }

        static Prototype* getType2Value1()
        {
            return type2value1->clone();
        }
};

int main()
{
    ObjectFactory::initialize();
    Prototype* object;

    /* All the object were created by cloning the prototypes. */
    object = ObjectFactory::getType1Value1();
    std::cout << object->getType() << ": " << object->getValue() << std::endl;

    object = ObjectFactory::getType2Value1();
    std::cout << object->getType() << ": " << object->getValue() << std::endl;

    return 0;
}

Download the fully working example from github.

Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Example of `prototype' design pattern
# Copyright (C) 2011 Radek Pazdera

import copy

class Prototype:

    """ Object, that can be cloned.

    This is just a base class, so the clone() method
    is not implemented. But all subclasses have to
    override it.
    """

    _type  = None
    _value = None

    def clone(self):
        pass

    def getType(self):
        return self._type

    def getValue(self):
        return self._value

class Type1(Prototype):

    """ Concrete prototype.
    
    Implementation of Prototype. Important part is the
    clone() method.
    """

    def __init__(self, number):
        self._type = "Type1"
        self._value = number

    def clone(self):
        return copy.copy(self)

class Type2(Prototype):
    """ Concrete prototype. """

    def __init__(self, number):
        self._type = "Type2"
        self._value = number

    def clone(self):
        return copy.copy(self)

class ObjectFactory:

    """ Manages prototypes.

    Static factory, that encapsulates prototype
    initialization and then allows instatiation
    of the classes from these prototypes.
    """

    __type1Value1 = None
    __type2Value1 = None

    @staticmethod
    def initialize():
        ObjectFactory.__type1Value1 = Type1(1)
        ObjectFactory.__type2Value1 = Type2(1)
        
    @staticmethod
    def getType1Value1():
        return ObjectFactory.__type1Value1.clone()

    @staticmethod
    def getType2Value1():
        return ObjectFactory.__type2Value1.clone()


def main():
    ObjectFactory.initialize()

    instance = ObjectFactory.getType1Value1()
    print "%s: %s" % (instance.getType(), instance.getValue())

    instance = ObjectFactory.getType2Value1()
    print "%s: %s" % (instance.getType(), instance.getValue())

Download the fully working example from github.

Sources

String Generation for Brute-force Attacks

Everyone knows what a brute-force attack is. One of the most trivial (and yet pretty useful) methods of cracking passwords and breaking access keys. The idea is simply trying all possible sequences of input characters, until you guess the right combination. The thing is, that it might take some time. Actually, sometimes it might take literally ages, due to large number of possible outcomes. The faster our machines (and algorithms!) get, the lesser time it takes to break in using brute-force attack.

One of the key components in this technique is an algorithm that generates the input combinations. It’s run every time in the main loop. Well, the loop is pretty much generate a password, try it and try again. This article will present a couple of simple implementations of string sequence generators in various languages.

Python implementation

Here is code for a most basic example in Python. It’s a simple recursive function that is able to generate strings up to infinite length. I use a list instad of string in this example, because strings in python are immutable. You need to convert it to string ("".join(list)).

def next(string):
    if len(string)
        string.append(chr(0))
    else:
        string[0] = chr((ord(string[0]) + 1) % 256)
        if ord(string[0]) is 0:
            return list(string[0]) + next(string[1:])
    return string

Download the whole example from github.

This example is simple. It tries every possible combination which takes it’s success rate up to 100 percent. You just can’t miss anything if you try them all, right? But a lot of the characters from ASCII table are non-printable, weird and people don’t use them for passwords. So you spend a great amount of time by trying out combinations that are extremely unlikely to ever occur. It would be pretty awesome if there was some way of saying what characters can be part of a password string and use only them. The number of possible outcomes lowers a lot by this optimization while the chance to miss is still almost zero. I made a some alternations to the next() function above:

import string
ALLOWED_CHARACTERS = string.printable
NUMBER_OF_CHARACTERS = len(ALLOWED_CHARACTERS)

def characterToIndex(char):
    return ALLOWED_CHARACTERS.index(char)

def indexToCharacter(index):
    if NUMBER_OF_CHARACTERS
        raise ValueError("Index out of range.")
    else:
        return ALLOWED_CHARACTERS[index]

def next(string):
    if len(string)
        string.append(indexToCharacter(0))
    else:
        string[0] = indexToCharacter((characterToIndex(string[0]) + 1) % NUMBER_OF_CHARACTERS)
        if characterToIndex(string[0]) is 0:
            return list(string[0]) + next(string[1:])
    return string

This snippet above works only with printable characters (as specified in python’s string module). You can also change the subset of characters it works with by changing the value of ALLOWED_CHARACTERS constant. The whole source is again available at github.

Next time I’ll look into a C implementation of the technique and a comparison of speed between the two languages.

Design Patterns: Builder

It’s time for another design pattern example and today it’s gonna be builder design pattern! Another creational pattern, as the name suggests. And how does it work?

Using builder pattern is something like outsourcing a constructor into a separate class. It deals with building object that have a lot of various parts. This increases the level of complexity of the object, which often results in complicated initialization. Builder splits the construction into a number of stages in which different parts are built. The builder is an abstract class (or an interface) that is able to build various components of the final object, but not the object itself. The building process is controlled by another class — a director. Director has an instance of builder and uses it to build the final object. Decides what components will be used and at the end, the director’s output is the final fully initialized object.

Class diagram

Class diagram for builder pattern (source: wikipedia.org)

The example, I will be working with is a process of assembling a car. Don’t worry, I won’t go through each screw in the engine, I don’t know much about that stuff anyway :-). The point is, a car is quite complicated thing to build and that’s exactly what we’re looking for.

So take this, we’re in a factory that builds two types of cars: a big-ass SUVs and tiny smarts. The both cars have virtually the same parts. Well, both have wheels, an engine, some windows (not to be confused with the operating system, that would be a deadly weapon, a car with Windows XP installed) and maybe doors. They might differ in their attributes — size, shape, used material, but both are used for the same purpose and in our example, they will be of the same type.

Then, there are two types of guys in our store — builders and a director. Builders work on the low-level. Every builder knows how to assemble various parts of a car (an engine, car body, a wheel). There might be multiple builders for multiple types of cars — nobody can understand everything. The director then takes those parts from a builder and puts them together so they form a working vehicle. The director controls the whole construction process, does important decisions and takes responsibility for the product while builders take care of assembling the smaller basic parts.

When a customer comes to the director and says, `Hi, can I have one Big Ass SUV?’ The director’s like, `Sure buddy, gimme a sec’, and goes into the back of the store to the builders. He asks them for the parts and assembles them together. After while he comes back and hands the customer the keys to his new chick magnet. If something goes wrong during this process, for instance builder cannot give him four wheels because they’ve run out of tires, the director apologizes to the customer, that they cannot build him the SUV today (maybe next time).

In other words, there are one algorithm for setting up an object from some parts, which is implemented in director class and it’s independent from the exact types of the basic parts. Basic parts are built by builders, that are associated with the director. The final shape of the product is determined by both.

Difference between Builder and Abstract Factory

The Builder pattern is somewhat similar to the Abstract Factory. This pattern extends the abstract factory with the director object which makes the design more flexible. Some initialization is often associated to the building process as well.

Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

Builder often builds a composite while Abstract Factory outputs a set of objects.

C++

This time the code is not included in the post due to it’s length. It’s available only through github.
Download C++ example

Python

Same as the C++ code. You can see it at github.
Download Python example

Sources

Documenting Python Code with Sphinx

One of the essential tasks in software development is documenting your code. With no documentation, hardly anyone will be able to understand your code and therefore contribute to your project. Sometimes you might find even yourself looking at your own code wandering, “What the hell is this supposed to mean?” Well, that’s where documentation comes in!

Good idea is to include documentation right into the source files. First of all, it helps coders read the source, because if they don’t get something, the documentation is right there! It’s much easier to maintain correct documentation. If you change something, you also change it 10 lines above in the documentation string. There are lots of utilities for analyzing source files and generating documentation from them. JavaDoc for Java, doxygen for C++ and Sphinx for Python.

I assume you know the awesome-looking Python docs, right? Well, that documentation is generated by Sphinx! In this post I’ll try to explain how to get sphinx and most importantly how to get that sweet-looking documentation out of it :-).

Installation

Sphinx is distributed as a python module, so you can use easy_install to get it. Install sphinx and all the dependencies by writing:

$ sudo easy_install sphinx

Easy install is a part of setuptools. So if this doesn’t run anything you probably need to install them. Look for package python-setuptools in your distribution’s repositary.

Setting up the doc folder

Documentation is usualy placed in a separate folder in your project directory. It’s really up to you, but I recomend using doc/ folder. Then you need to setup basic files for sphinx in that particular folder (sphinx calls it a source directory). This can be done by sphinx-quickstart command that will guide you through the whole setup process. The important thing here is to answer yes to the question of enabling autodoc extension. This extension then collect the documentation from your code.

$ mkdir doc
$ cd doc/
$ sphinx-quickstart

Writing documentation

The above mentioned sequence of commands should create a basic directory structure of your sphinx documentation. Somewhere in that structure (it depends on how did you answer to the questions of sphinx-quickstart) will be an index file of the whole docs. By default it will be called index.rst. Content of this file is in reStructured text. It’s a syntax for formating plain text documents. It’s not very hard to learn. Using either rst quick reference, sphinx guide or my personal favorite way — ripping off python docs.

On every html page generated by sphinx is a link to the source rst file it were generated from. And so it is in the python docs. The link is at the bottom of the menu right above the search box. You see, the documentation of python is not only quite large, but also really well formed. So by looking at that you’ll be soon able to write some pretty good docs yourself.

Sphinx documentation example

If you decide to crate a new page, you can simply add a file to the doc/ directory and sphinx will find it and include it into the documentation.

Documentation from docs string isn’t included automatically like in doxygen. You need to specify where to include what. In-depth explanation on how to do that is here.

Conclusion

Well, this was my very brief experience with sphinx. It’s a great tool for creating documentation for your python projects. Hopefully, I’ll get back to it at some point in the future and expand this article.

Sources

Design Patterns: Abstract Factory

I’m trying to keep up the tempo and do a pattern a day, so here goes another one! Today it’s abstract factory. I wrote a post about the factory method yesterday and this one (as you can guess) is somewhat similar.

What exactly is an abstract factory? It’s from the creational patterns group, so it controls object creation. The intent is to abstract creating whole families of objects without specifying concrete classes. We have a class called abstract factory that controls the creation. The class is abstract, because it has only virtual methods. This interface is later implemented by concrete factory classes. These object factories then creates a matching set of objects under some circumstances.

Take this for instance, you have a certain set of objects, that works on Windows and a certain set of objects, that does the same job, but under Linux. In this case there will be two subclasses of the abstract factory class. One that will create objects for windows and the second one for Linux. At the runtime, you create an instance of either one, depending on what platform is the program running on and the factory will build the appropriate set of objects.

More in-depth explanation is here. I’m trying to focus at the code examples:

User Interface Example with Gimp

The code is not as straight-forward as the previous, I’ll try to explain it with some more detail. I used a picture of GIMP UI to illustrate better what I mean, but this has absolutely nothing to do with the GIMP’s code and how it’s implemented!

Gimp UI

Gimp User Interface Example

So take this for instance. Your task is to write user interface for a program. The interface design says, there will be three windows (like there are in gimp). Also, among the requirements, there is one that says your code has to work natively with both — KDE and Gnome desktop environments. Each of these is built on a different toolkit. KDE uses Qt, Gnome uses Gtk. So somewhere in your code, you’ll need to check, what environment is available and construct an object, that will work with the current environment. This is where the abstract factory comes handy.

You will encapsulate the creation of all the UI components (in this case the three windows) into the abstract factory. Abstract factory is a class, something like this:

class UIFactory
{
    virtual void Window* getToolboxWindow() = 0;
    virtual void Window* getMainWindow() = 0;
    virtual void Window* getLayersWindow() = 0;
};

It’s an abstract class — it says, “I can get you the user interface”, but it doesn’t say how or what exactly are you going to recieve. Then, for each case (in our example it’s Qt and Gtk), there will be a subclass that implements this abstract factory, saying “from me, you’re going to get Qt/Gtk windows”. Then in your program, you check what your environment is and create an instance of QtUIFactory or GtkUIFactory. At this point you can be sure, that all windows will be constructed with support of the correct environment.

C++

Here is the implementation of the above in C++.

class Window
{
    protected:
        int width;
        int height;
        std::string toolkit;
        std::string type;

        Window(std::string usedToolkit, std::string windowType)
            : toolkit(usedToolkit), type(windowType)
        {}

    public:
        std::string getToolkit();
        std::string getType();
};

class GtkToolboxWindow : public Window
{};

class GtkLayersWindow : public Window
{};

class GtkMainWindow : public Window
{};


class QtToolboxWindow : public Window
{};

class QtLayersWindow : public Window
{};

class QtMainWindow : public Window
{};

/* This is the abstract factory. */
class UIFactory
{
    public:
        virtual Window* getToolboxWindow() = 0;
        virtual Window* getLayersWindow() = 0;
        virtual Window* getMainWindow() = 0;

};

/* Factory for Gtk toolkit */
class GtkUIFactory : public UIFactory
{
    public:
        Window* getToolboxWindow()
        {
            return new GtkToolboxWindow();
        }

        Window* getLayersWindow()
        {
            return new GtkLayersWindow();
        }

        Window* getMainWindow()
        {
            return new GtkMainWindow();
        }
};

/* Factory for Qt toolkit */
class QtUIFactory : public UIFactory
{
    public:
        Window* getToolboxWindow()
        {
            return new QtToolboxWindow();
        }

        Window* getLayersWindow()
        {
            return new QtLayersWindow();
        }

        Window* getMainWindow()
        {
            return new QtMainWindow();
        }
};

int main()
{
    UIFactory* ui = 0;

    /* Check what environment is running
and create appropriate factory. */
    if (/* Gtk == */ true)
    {
        ui = new GtkUIFactory();
    }
    else
    {
        ui = new QtUIFactory();
    }

    /* Use the factory to build interface. */
    Window* toolbox = ui->getToolboxWindow();
    Window* layers = ui->getLayersWindow();
    Window* main = ui->getMainWindow();

    /* See what have we recieved. */
    std::cout << toolbox->getToolkit() << ":"
              << toolbox->getType() << std::endl;

    std::cout << layers->getToolkit() << ":"
              << layers->getType() << std::endl;

    std::cout << main->getToolkit() << ":"
              << main->getType() << std::endl;
}

The code has been shortened a little. The fully working source file is available, as per ushe at github.

Python

And here is the Python version.

class Window:
    __toolkit = ""
    __purpose = ""

    def __init__(self, toolkit, purpose):
        self.__toolkit = toolkit
        self.__purpose = purpose

    def getToolkit(self):
        return self.__toolkit

    def getType(self):
        return self.__purpose

class GtkToolboxWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "ToolboxWindow")

class GtkLayersWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "LayersWindow")

class GtkMainWindow(Window):
    def __init__(self):
        Window.__init__(self, "Gtk", "MainWindow")


class QtToolboxWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "ToolboxWindow")

class QtLayersWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "LayersWindow")

class QtMainWindow(Window):
    def __init__(self):
        Window.__init__(self, "Qt", "MainWindow")

# Abstract factory class
class UIFactory:
    def getToolboxWindow(self): pass
    def getLayersWindow(self): pass
    def getMainWindow(self): pass

class GtkUIFactory(UIFactory):
    def getToolboxWindow(self):
        return GtkToolboxWindow()

    def getLayersWindow(self):
        return GtkLayersWindow()

    def getMainWindow(self):
        return GtkMainWindow()

class QtUIFactory(UIFactory):
    def getToolboxWindow(self):
        return QtToolboxWindow()

    def getLayersWindow(self):
        return QtLayersWindow()

    def getMainWindow(self):
        return QtMainWindow()

if __name__ == "__main__":
    gnome = True
    kde   = not gnome

    # What environment is available?
    if gnome:
        ui = GtkUIFactory()
    elif kde:
        ui = QtUIFactory()

    # Build the UI
    toolbox = ui.getToolboxWindow()
    layers  = ui.getLayersWindow()
    main    = ui.getMainWindow()

    # Let's see what have we recieved
    print "%s:%s" % (toolbox.getToolkit(), toolbox.getType())
    print "%s:%s" % (layers.getToolkit(), layers.getType())
    print "%s:%s" % (main.getToolkit(), main.getType())

The whole thing at github.

Sources

Unit Testing in Python

I think, I don’t need to tell you, how important is testing your code in software developement. One way of doing so is writing unit tests. Unit tests are an automated set of test cases. These test cases are there to make sure, that the code does exactly what it should, nothing more and nothing less.

Every once in a while you change something in the software, you simply just run the tests and see if the changes didn’t break something that was working fine beforehand. A set of good tests will increase your confidence while releasing your software and (believe me) those stupid unit tests of class interface can save literally weeks of debugging.

In agile, you’re supposed to write the tests before you implement the actual functionality. That’s how the tests are important :-). What are our testing possibilities in Python? Well, let’s have a look …

Unittest

Python itself (all hail!) provides pretty good testing framework caled unittest. Let’s have a look how it works.
In the center of it all is a class unittest.TestCase. While creating an unit test, you simply create a derived class from it. Here’s an example how could a test file look like:

# Import tested modules
import example

# Import unittest
import unittest

# Test definitions
class TestExample(unittest.TestCase):
    def testCaseExample(self):
        self.assertEqual(1,1)

# Run test
if __name__ == "__main__":
    unittest.main()

You should create a file like this for every module in your code. Now, let’s have a look on how to organize the tests in your project. The best practice is to separate them all into a folder called test. Directory tree of your project might look like this:

project/
  |-src/
  |  |-module.py
  |  |-class.py
  |-test/
  |  |-test_module.py
  |  |-test_class.py
  |-run_tests.sh

This is nice, but now that you’re sources are in a separate directory it’s a little tricky to be able to import your modules into your tests and then run all the tests. For that I have written a simple script run_tests.py that will do it for you. Here it goes:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, re
import unittest

TESTED_CODE = "src/"  # Path to tested code.
TEST_CODE   = "test/" # Path to test code.

sys.path.append(TESTED_CODE)
sys.path.append(TEST_CODE)

# Import all the tests from 'test/'.
for testFile in os.listdir(TEST_CODE):
    if re.match("^test_.+\.py$", testFile):
        exec "from %s import *" % testFile[0:-3]

# Run the tests.
if __name__ == "__main__":
    unittest.main()

For more on this subject, see the unittest documentation.

Here is an example setup of unit tests for your project. It contains a convenient script, that runs all the tests in the test/ directory.

Nose

One of key features of an unit testing framework is simplicity. You need to be able to create new tests fast and efficiently, because you’re gonna be doing it A LOT. The harder it is to write new tests, the more you’ll be skipping them and that’s a highway to coder’s hell.

Using the Python’s built-in unittest framework isn’t that time-consuming, but there is still some space for improvement. That’s where nose comes in.

It’s a third-party testing framework for Python and it comes with a load of other cool featuers. I personaly have never used it, because I find the built-in framework quite sufficient for my needs, but if you look for something more robust, nose is definitely worth trying.

Sources

Design Patterns: Factory Method

Another design pattern today! The second most common after the singleton is in my opinion factory method. It’s a creational design pattern, that’s useful while you need to control creation process of the objects a little more than by a constructor.

For instance you might want to decide what subclass to create at the runtime rather than while writing the code. Or you don’t care what subclass will be constructed. Factory method in some more advanced implementations also allows reusing old objects insead of always creating new instances. The factory method will give you an object when you request it, but the creation process is encapsulated. That encapsulation is enforced, and allows an object to be requested without inextricable coupling to the act of creation.

Detailed description of the design pattern can be found at sourcemaking.com. I’ll just throw in the code. In my examples, there’s a base class — a Cup and two subclasses RedCup and BlueCup. The base class has a factory method that will get you a cup of the color you like.

C++

class Cup
{
    public:
        Cup()
          : color("")
        {}

        std::string color;

        /* This is the factory method. */
        static Cup* getCup(std::string color);
};

class RedCup : public Cup
{
    public:
        RedCup()
        {
            color = "red";
        }
};

class BlueCup : public Cup
{
    public:
        BlueCup()
        {
            color = "blue";
        }
};

Cup* Cup::getCup(std::string color)
{
    if (color == "red")
        return new RedCup();
    else if (color == "blue")
        return new BlueCup();
    else
        return 0;
}

/* A little testing */
int main()
{
    /* Now we decide the type of the cup at
* runtime by the factory method argument */
    Cup* redCup = Cup::getCup("red");
    std::cout << redCup->color << std::endl;

    Cup* blueCup = Cup::getCup("blue");
    std::cout << blueCup->color << std::endl;
}

The whole source file is available on git.

Python

class Cup:
    color = ""

    # This is the factory method
    @staticmethod
    def getCup(cupColor):
        if (cupColor == "red"):
            return RedCup()
        elif (cupColor == "blue"):
            return BlueCup()
        else:
            return None

class RedCup(Cup):
    color = "red"

class BlueCup(Cup):
    color = "blue"

# A little testing
redCup = Cup.getCup("red")
print "%s(%s)" % (redCup.color, redCup.__class__.__name__)

blueCup = Cup.getCup("blue")
print "%s(%s)" % (blueCup.color, blueCup.__class__.__name__)

The whole source text is available on git.

Sources