Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

Wednesday, January 13, 2010

Practical Php Patterns: Singleton

This is the fifth post from the Practical Php Pattern series, which will touch the majority of the known design patterns, with a special look at their application in a php context and code samples.

Today we will discuss the Singleton pattern, the most controversial creational pattern.
A Singleton is a global point of access for a resource that must have only one instance in the whole application: database connections, http streams, and similar objects are the typical examples of such a class.
This behavior is implemented trough a static method which returns a lazy-created instance, and by rendering the constructor private to avoid creation of an instance from outside the class code.
The problems of a Singleton class are the same of its non object-oriented equivalent: a global variable. The Api of Clients of the Singleton lies, because they do not declare in any signature that they are taking advantage of the Singleton's capabilities; moreover, global mutable state is introduced and encapsulation is disregarded.


There is a famous credit card example, which describes the usage of a CreditCard class. One day Misko Hevery was writing some tests in a system he does not know very well, to improve his knowledge of the codebase.
He wrote this code:
testCreditCardCharge() {
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100);
}
The test ran, and at the end of the month he got the bill and see he was out $100! The story is probably made up, but you get the point: if a Client references Singletons, you have no idea of what can happen when calling a method.
The Api of CreditCard would have been honest if it was like:
testCreditCardCharge() {
  CreditCard c =  new CreditCard(
    "1234 5678 9012 3456", 5, 2008);
  c.charge(100, creditCardProcessor);
}
Have you ever seen a CreditCard that can be used without a POS?

In my opinion the classic Singleton pattern is adequate only if the static instance has no state, or it is an utility without side effects which you may want to substitute. The sample code reflects this weltanschauung.
There are people that subclass Singletons, but if you feel the need to write a subclass it probably means you are already gone too far. Refactor the code to inject the Singleton as a collaborator of Client.

PARTICIPANTS:
  • Singleton: class that manages to keep one and only one instance of itself.
  • Client: every class that references a Singleton.
The code sample follows.
<?php
/**
 * The most harmless example of a Singleton I can think of is a Logger.
 * However, I feel that injecting the Logger or managing events with an
 * Observer pattern would be better here.
 * This Singleton infringes every rule of testability:
 * - constructor does real work
 * - destructor does other work
 * - constructor is private, you cannot instantiate it in tests
 * - instance is static, you cannot throw it away
 */
class LoggerSingleton
{
    private static $_instance;
    private $_fp;
    
    /**
     * We need only one instance, which will lock the file
     * from further editing.
     */
    private function __construct()
    {
        $this->_fp = fopen('log.txt', 'a');
    }

    public function __destruct()
    {
        fclose($this->_fp);
    }

    public function log($text)
    {
        $line = $text . "\n";
        fwrite($this->_fp, $line);
    }

    /**
     * An instance of this class is lazy created and returned.
     * No further instances are created if there is already one available.
     * This method is the standard way to create a Singleton.
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

/**
 * The Client receives a name and returns a welcome message, while
 * logging the operation.
 * *Little* side effect: it writes a file.
 */
class Client
{
    public function createWelcomeMessage($name)
    {
        LoggerSingleton::getInstance()->log("Greeted $name");
        return "Hello $name, have a nice day.\n";
    }
}

// isn't it strange that these two lines write a file on disk?
$client = new Client();
echo $client->createWelcomeMessage('Giorgio');
The one instance myth is overrated, and there are other means to achieve the same behavior from a class. Test suites could have dozen of instances of "unique" services and connections (some of them as Fakes and Stubs); in fact, a proof of testability and good design consists in being able to run two applications in the same php script, Jvm or main method.
The difference is that maintaining a unique instance is correct, but only within the boundaries of an application. If you control the creation process, your factories will never create more than one instance of a critical resource. Using a Singleton extends this uniqueness along all the execution environment and hides a crucial dependency under the carpet, effectively causing hassle to everyone trying to figure out what is going on, in debugging as in testing.

Tuesday, November 10, 2009

Mocking and template methods

As you probably know, stubbing or mocking is a practice used in unit testing where a class methods are substituted via subclassing with test-friendly versions of themselves. The difference between stubbing and mocking resides in the place where the assertions are made, but it is not the main topic of this post.
The need for small and cohesive interfaces is particularly perceived while mocking a class. We typically want to test in isolation a unit and write mocks for its collaborators without going mad.
Let's see an example of a class I may want to mock:
class NakedEntity
{
    public function getMethods()
    {
        return $this->_class->getMethods();
    }

    public function getMethod($name)
    {
        $methods = $this->_class->getMethods();
        return $methods[$name];
    }
    
    public function hasMethod($name)
    {
        $methods = $this->_class->getMethods();
        return isset($methods[$name]);
    }

    // other methods, constructor...
}
As I said earlier, mocking is effective if there is a small interface to mock. Note that every class defines an implicit interface: the set of its public methods. Sometimes the interface comprehends several methods that give access to the same data or behavior, and that have to be present to avoid abstraction inversion. In this particular case, if I defined only getMethods() to conserve a small and cohesive interface, every class that depends on NakedEntity would have to implement the other two missing methods.
Mocking all three methods of NakedEntity in phpunit means writing this:
$mock = $this->getMock('NakedEntity');
$mock->expects($this->any())
     ->method('getMethods')
     ->will($this->returnValue(array('doSomething' => ..., 'foo' => ...)));
$mock->expects($this->any())
     ->method('getMethod')
     ->will($this->returnValue(...));
$mock->expects($this->any())
     ->method('hasMethod')
     ->will($this->returnValue(true));
Compare this to the creation of a real NakedEntity. I should definitely create a real object to save test code, but the unit tests will then not be executed in isolation and I will have to define a mocked NakedClass object (the $this->_class property) and break the Law of Demeter.
Moreover, the mocking capabilities of phpunit are limited and for example we cannot define different return values based on the parameters (a real subclass is needed in that case) without a callback. I could mock only the methods effectively used from the SUT, but I don't really know which of them are really called (since they are more or less equivalent) and I want to refactor the SUT without changing the tests.
So I found a 2-step alternative solution.

Step 1: convenience methods become template methods
I started with refactoring the NakedEntity class:
class NakedEntity
{
    public function getMethods()
    {
        return $this->_class->getMethods();
    }

    public function getMethod($name)
    {
        $methods = $this->getMethods();
        return $methods[$name];
    }
    
    public function hasMethod($name)
    {
        $methods = $this->getMethods();
        return isset($methods[$name]);
    }

    // other methods, constructor...
}
The users of getMethods() are now template methods, and the base method (primitive operation in design patterns jargon) can be subclassed to provide alternative behavior. The subclass can be implemented as a real reusable class, which will include a setMethods() utility method (no pun intended), or via mocking.

Step 2: mock the base method
Now only getMethods() need to be substituted:

$mock = $this->getMock('NakedEntity', array('getMethods'));
$mock->expects($this->any())
     ->method('getMethods')
     ->will($this->returnValue(array('doSomething' => $myMethod, 'foo' => ...)));
$this->assertEquals($myMethod, $mock->getMethod('doSomething')); 
 
This approach works well because the contract of NakedEntity is already cohesive and the different methods provide different ways to do the same thing. The template methods contain nearly no logic and they are exercised in unit tests which are not their own: it is a very small trade-off because it is highly improbable that they will break and cause another class unit tests to fail without reasons. The template methods in this case are only glue code.
Don't use this testing pattern as an excuse to write many public methods: you should indeed break up a class in different units if its contract grows too much. You can implement a Decorator pattern if convenience template methods are implementing business logic on a public method, or it may be the case that your class is doing too much and the Api is too complicated. Another viable solution if you have an explicit interface instead of a concrete class is creating a reusable Fake implementation which will contain the convenience methods as well.
In conclusion, if you have a contract with many cohesive and dumb methods, which relies on a central one to provide data, you can create template methods and reuse them in other unit tests, via subclassing of the primitive operations.

Wednesday, October 28, 2009

Php login with Zend_Auth

Zend_Auth is the component of the Zend Framework which provides a standard authentication mechanism for web applications users. It has few dependencies (on Zend_Loader and on Zend_Session for default persistence of the authentication) and, as other framework components, will let you concentrate on the user experience instead of worrying about boilerplate code.

Zend_Auth is the facade class for this component and it is implemented as a Singleton. If you want to access it in your business classes wou may want to inject it in the constructor, relieving your code from coupling and make it simpler to unit test.
The shortest way to access Zend_Auth is by requesting its Singleton instance (I hope you will write this specific code only in a factory if you have a well-designed object-oriented application):
<?php
$auth = Zend_Auth::getInstance();
The $auth object has some methods which encapsulate the functionalities you have been busy reinventing for every project you are participating in. For instance to authenticate a user, just set up an adapter (more information on this later in the post) and write the following code:
$result = $auth->authenticate($adapter);
$result is a Zend_Auth_Result object, and has a method getCode() which you can call to access the result code created by the adapter during the request for authentication. 
switch ($result->getCode()) { 
            case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
            case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                // bad...
                break;
    
            case Zend_Auth_Result::SUCCESS:
                // good...
}
Maybe you want to check if your user is already authenticated before redirecting him to a login form:
if (!$auth->hasIdentity()) {
    // redirect wherever you want... 
}
or you want to know the username that was passed to the adapter (again, more on setting up the adapter of your choice and passing it username and password later):
$name = $auth->getIdentity();
or certainly you want in some place to logout the user, as he chose by pressing the Logout button:
$auth->clearIdentity();

As a side note, remember that username and password assume the generic name of identity and credential troughout all classes contained in the Zend_Auth component. Moreover, the default storage for Zend_Auth successful authentication attempts is Zend_Session, which means a session cookie will be set on the client and the username will be saved as a session variable. Typically the session lifecycle will last till the browser closure and you have to provide alternate storage if you want a permanent authentication a la facebook.

An adapter is an object that bridges Zend_Auth with different authentication servers: it links together the infrastructure code of Zend_Auth with your business and domain layer. For instance, you can login via Ldap or via a relational table, by specifying the identity and credential column names:
$authAdapter = new Zend_Auth_Adapter_DbTable(
    $dbAdapter,
    'oss_users',
    'nick',
    'pwd'
);
where $dbAdapter is an instance of Zend_Db.
Don't want to tie your authentication with another zf component? No problem, it is indeed very simple even to create your adapter which uses PDO or whatever you want, even ini files. I just work recently on a server where PDO was not available and I could only call mysql_query() to access the database. Pragmatically, I wrote this adapter in about five minutes:
<?php

require_once 'Zend/Auth/Adapter/Interface.php';
require_once 'Zend/Auth/Adapter/Exception.php';
require_once 'Zend/Auth/Result.php';

class MyAuthAdapter implements Zend_Auth_Adapter_Interface
{
    private $_table = 'oss_users';
    private $_username;
    private $_password;

    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }

    /**
     * @throws Zend_Auth_Adapter_Exception
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
        $q = mysql_query("SELECT * FROM $this->_table WHERE nick = '$this->_username'");
        if (!mysql_num_rows($q)) {
            return $this->_getResult(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND);
        }
        if (mysql_num_rows($q) > 1) {
            throw new Zend_Auth_Adapter_Exception('Too many results.');
        }

        $row = mysql_fetch_array($q);
        if ($row['pwd'] != $this->_password) {
            return $this->_getResult(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID);
        }

        return $this->_getResult(Zend_Auth_Result::SUCCESS);
    }

    protected function _getResult($code)
    {
        return new Zend_Auth_Result($code, $this->_username);
    }
}
Of course, $username and $password should be quoted in some way before passing them to the constructor, since PDO is not used here. After having created this object, I only had to pass it to Zend_Auth:: authenticate() to complete the process as I explained earlier in this post.

I hope you feel the power of Zend_Auth and the time it can save for you in many different php projects. If you already have experience with Zend Framework, it is the right time to start using a standard solution.

Monday, October 12, 2009

Object-oriented myths

I think object-oriented programming techniques should be explained with a context and not shouted out loud as philosophical principles. Sometimes these techniques are misinterpreted, or exaggerated and used as a weapon against oop proponents.
Some popular myths about oop have risen in the programming world, particularly in the php continent where object orientation is still in its infancy. I want to debunk these legends to show that good oop is actually easier than you think. For instance, Dependency Injection is one of the best thing that can happen to your code.


"You should not expose public fields. Write getters and setters instead."
The point of encapsulation is to protect client classes from changes in the collaborators. In what is using a set*() method different from a public field, for the cause of encapsulation?
There are some classes which only responsibility is to maintain state. We encounter them in every project, being their names User, Post, CreditCard, String, Regex and so on. It is correct for this type of classes to have getters and setters to change their internal state and fulfill their requirements.
The other type of classes are services: stateless objects which do complex work, are not serializable and may have internal and external dependencies, towards other services or processes. These classes should not have any get*() or set*() method, since they are by definition stateless and the list of getters will break encapsulation. If I were a client class I would require a BookRepository object to search books, because I use it to... search books and not to change the underlying database calling BookRepository::setDb(Zend_Db $db). It's not my job to pass the collaborators in: I use the object only to search books.
If you find a complex service class which also has a state, the most useful thing to do is to break up the class in little ones because the responsibility is too high for a single unit. Testability and cohesion will improve.
So without setters, how I get collaborators references in, for example, a ServiceClass object private fields? You can create them directly in ServiceClass methods (bad) or realize Dependency Injection, passing them in the constructor of ServiceClass. A Factory will then call new, passing in the collaborators and encapsulating the creation. This practice leads us to the next myth.

"Why using a factory? There's no point in creating an object only to create another one."
The process of an object's creation can be intensive and complicated. If you use Dependency Injection (and you probably should as it is a standard practice for producing solid object-oriented code), every object needs its collaborators passed in the constructor, and the collaborators need other collaborators and so on. It's useful to abstract away this process in a Factory class whose methods perform the construction in one centralized place. Again, entity objects like Strings, Users and Posts are a bit special and using a Factory for them is not required, provided that they don't even had collaborators.
Though, if you find yourself creating a factory and subsequently, in the next line of code, using its methods to create a business object, chances are the design can be improved. The principle is that objects should ask for things, and not look for them.
Let's make the following assumptions:
  • You write object-oriented applications, so all your code is kept in classes. This is not necessarily true for hybrid languages like php.
  • You strive for minimizing the coupling of your components, respecting the Law of Demeter. You want to reuse classes and you want to be able to test them in isolation.
So start with examining where you are creating a BusinessObject in a class Client. The possible cases are three (actually two):
  • (not possible) BusinessObject has a longer lifecycle than Client, so you cannot create it in Client. Ask for it in the constructor.
  • BusinessObject has the same lifecycle of Client: it's a collaborator. So stop using a factory and simply ask for BusinessObject in the constructor of Client.
  • BusinessObject has a shorter lifecycle than Client: it must be created at a specific time, when some method on Client is called.
The latter case is the most interesting one. If BusinessObject is an entity, you can create it directly: there are no external dependencies to inject and there is little behavior to mock out in tests. If BusinessObject is a service class, with one or more external dependencies and more than a bit of behavior, you should indeed use a Factory to encapsulate its creation. But since you strive to reduce coupling, Client must not know if BusinessObject calls methods on an hundred different objects or returns prepackaged results. So you should pass in a Factory object in the constructor of Client: this solution resembles an Abstract Factory pattern, with the difference that we are focusing on lifetimes and not on extensibility and introduction of new subtypes.
In sum, all direct service object creation (use of the new operator) should be encapsulated in Factories, which can be used in the application bootstrap or passed in the constructor of the Client class if you need object creation as a business requirement (and the object is more complex than a String). Obviously if you are using setter injection it does not make a great difference, but the Api will be more cluttered. If your setters does not accept multiple calls to change collaborators, they have my blessings.
Warning: all the class names used are examples. For instance Client and BusinessObject are two classes that could also be called A and B. I often use Client to denote a class which is attempting to create an object, according to the GoF terminology. BusinessObject is a generic name for a class, more readable than Foo and Bar.

This post is becoming too long to not lose focus, so I'll continue tomorrow with the rest of object-oriented myths.
You may want to subscribe to the feed to discover the other myths as soon as they are published.

Monday, October 05, 2009

Readable code is not for maintenance only

Emphasis is often put on writing readable code, for the sake of maintenance. But you forget and reread code every minute, not in 2016, so why worrying about the far future when you should worry about tomorrow?

Long term maintenance issues
Even your code, after six months, becomes a stranger to you. Especially if you have improved your coding skills meanwhile, the implementation will be very hard to grasp at a glance. While it can be possible and recommendable to study and remember a software system's big picture, code at the low level inside public and private methods it's quickly forgotten: variable names and the general flow have to be analyzed again and again. To put is simply the human mind does not have the capability of memorizing every single line of code and implementation decision.
Though, there are some things a developer usually masters in his mind:
  • The general design of the system, as most new features require a knowledge of it to know which component should accomodate new classes and functions.
  • The Api of a widely utilized subsystems or class, like Zend_Form in php or the Collection interface in Java.
These are elements of the implementation which do not change very often, and that are refreshed in the developer's memory nearly every day. Usually there is powerful documentation on these arguments, but having a mental understanding of them is always more beneficial.
For the rest of the project, a typical programmer has only a mental model of how the entire system works, abstracted away from details like methods signatures and Uml sequence diagrams.
This is not a bad thing: human memory is less stressed and the code becomes the last, most refined step of the design. There is no need to study or document the details if the code is well written, and they change so often that keeping memory or documents in synchronization with the code is likely to be impossible. That's why Api documentation is automatically generated nowadays.
In this vision, encapsulation and decoupling are very important from the maintenance point of view not only for the isolation of changes in the code, but also for the use of developers time. If adding a feature or fixing a bug requires the analization of two or three classes, the developer will finish the job earlier than having to modify method signatures over a dozen of them. OCP strives for only adding new code, but you probably still have to read the old one even if you do not modify it: to subclass, to write a new implementation or to override a method you must know the original signatures and contract.
Moreover, meaningful variables, methods and parameters names aid the developer who has to deal with the code in his forced rapid study of the business logic. Everything you cannot remember has to be learned again and again and the faster this relearning process is, the faster the overall development will be.

Short term development issues
The trouble with the current readable code tips is the starting reason: helping maintainers because six months from now you will have forgotten everything about what you have written today. But if you shorten the time interval, the productivity boost given by readable and well-factored code is still valid: all the advantages discussed for maintenance can be applied in development as well, since maintenance is only deferred development.
No feature is integrated in a single pass: this is particulary stressed in the iteration-based methodologies, but it applies to many low level coding activities. TDD, for instance, prescribes to add a test at the time for the class under development, and to make it pass before repeating the cycle. Being the testing automatic or manual, I bet you start from a simplification of the feature and then refine the details: when you build a blog, first you add the article publishing form, then the visualization of posts, the search, a comment system. You can refine even further by adding new fields to the article model: date and time, tags, author. The process involves going back on the same code continuosly.
What activities do you carry out when making a new test pass? What do you do every single time before writing a single line of code?
You go back to the class you're writing and read again the code you have written yesterday, or two minutes ago to pass the test before. And if you do not have a photographic memory, you don't remember every character you wrote. You have to read it. The majority of the software developers in the world neither have such a memory.
Starting to write descriptive code helps your productivity now. If you do not believe it, try to program some serious application in assembly using (computer) memory addresses instead of variable names. You'll find yourself going back and forth in the source to copy addresses as if they were bad chosen variable names, confusing them continuosly.

Code is written one time, and then it is refactored or rewritten, which I see as a new writing process. It is read thousands of times instead. So what you focus on? Code that is short to write with three-characters identifiers or code that is simple to read?

What does the code in the picture do? I don't know. Even if I wrote it yesterday.

Friday, September 18, 2009

Zend Framework Api: what $options is?

I wanted to share an insight that repetitevely using and studying the Zend Framework API has given me. I know finding a lack in documentation can be annoying but ZF is usually very coherent in its API and I find out it is predictable also in this case, which is a good trait for a very large set of classes such as the one from Zend.

The tipical constructor of a Zend Framework class (or factory method) has a signature such as:
Zend_Form::__construct([mixed $options = null]);
and this always left me wondering what would $options contain, since I cannot found a documentation for this constructor. I depended on finding examples in the reference manual for what I want to do with my objects.
What I have learned is a convention widely used in Zend Framework main components and in the incubator: the options are passed to the setters after the mandatory construction process have taken place. This means that if we build a submit button in this way:
$button = new Zend_Form_Element_Submit('submit', array('ignore' => true, 'value' => 'Click me'));
the result is equivalent to:
$button = new Zend_Form_Element_Submit('submit');
$button->setIgnore();
$button->setValue('Click me');
So you can simply refer to the documentation of the particular setter you want to call in the constructor and provide a key in the array with the initial lowercase (to respect the Pear/Zend coding standard): setElementsBelongTo() will require a elementsBelongTo key.

It would be interesting to know if there is an official guideline to provide constructors like the ones in Zend_Form component or if do some classes follow a different convention: feel free to share what you know in the comments.

Featured post

A map metaphor for architectural diagrams

It is a (two-dimension) representation of a pipe. The map is not the territory , but in software engineering terms they are models of it....

Popular posts