Friday, April 09, 2010

Domain-Driven Design review

Domain-Driven Design: Tackling Complexity in the Heart of SoftwareDomain-Driven Design, by Eric Evans, is the masterpiece of the DDD movement. It introduced to the world the harvested experience of Evans in working on model-driven development on a variegate group of object-oriented projects, presenting it as a series of patterns and meta-patterns (such as the Ubiquitous Language), and ranging from the design of a single class to a large map of different applications.

A brief summary
DDD is a very dense book, and it is logically divided in four parts:
  • Putting the Domain Model to work, which covers the importance of the Ubiquitous Language and the centrality of the model of the application domain.
  • The building blocks describes the patterns used at the finer level, such as Entity, Value Object, Aggregate, Service, Factory and Repository. 
  • Refactoring towards deeper insight covers the continuos process of adapting the Domain Model to new insights and crunched knowledge, believing firmly that an hidden model exists and will be reached with a supple design. Modelling as described here is like applying an unification theory to software.
  • Strategic design introduces the techniques for large scale structure and separation of contexts, such as the famous Anticorruption Layer (although it is not the only communication medium between different Domain Models.)
In my opinion the third and fourth parts are the most difficult to digest, due to their abstractness (not everyone of us has worked at that scaling level) and the perceived distance from working code. In fact, the first two parts are rich in code samples, which gradually vanishes towards the end of the book while the view on object-oriented applications is taken to an higher level. Diagrams, both based on Uml and not, are preferred throughout the last chapters.

How to read it
Many people start reading DDD full of confidence, scheduling five chapters a day, only to struggle very quickly, usually in the second part, and abandone it. Even in my recently completed reading from cover to cover, I waited some time before starting the third part.
This book is intended as a series of patterns - notice the capital letters used for most of the names - those names are specific terms with a precise meaning. In the case of the Gang of Four book on design patterns, this made it hard to read cover to cover because of the lack of a common thread between the chapters.
But in this book's case, the main theme is the model-driven design practice that evolves from the finest level - the class and its methods - to BoundedContexts and Responsibility Layers. That said, the information contained is very dense and I have never read more than 15-20 pages on a given day. I suggest you do to the same or you risk burning out before reaching half of the book. Also taking notes is a mean that forces high focus of the content and may help.

Other resources
There is a lighter book freely available - Domain-Driven Design quickly - which promises to explain you DDD in 100 pages. Don't read it: when I tried, I understood a concept only as long as I have already read it on the original DDD book, and never learn anything on the new material. The original is 400-page long, but it is already condensed as much as possible.
A book that expands on the code samples and the design process is Applying Domain-Driven Design and Patterns, which is a good read to combine with DDD (in fact, it is 600-page long.) You may refer to it when you want more practical examples of a pattern treated in the original book.

In sum, this book is often cited as the DDD book, and in the future it may be considered the bible of real object-oriented development. If you have it on your shelf, I suggest you to read as much as you can beginning from the start, skipping only the fourth part if you do not ordinarily deal with large-scale applications.

Thursday, April 08, 2010

phpDay 2010 (plus discount code)

I will be at phpDay 2010, the Italian conference on PHP and related topics, as a speaker.
There are many talks in English from foreign speakers such as Fabien Potencier, but my talk is in Italian. It is scheduled for the last day of the conference, 15th May 2010.
http://www.phpday.it/session/architettura-e-testabilita
Talk page on joind.in
Architettura e testabilità: il design di un'applicazione può essere influenzato positivamente da diverse pratiche. La facilità di testing é condizione sufficiente per un architettura che garantisca semplice manutenzione e alta coesione dei componenti. Argomenti trattati: Dependency Injection, Law of Demeter, Design Pattern creazionali (Factory vs. Singleton), Api oneste.
If you are interested, you can book a seat here. I have a 20% discount code I can give you if you ask me via email, I'm not sure publishing it here is allowed.

Wednesday, April 07, 2010

HTTP verbs in PHP

While PHP is capable of performing HTTP requests towards external servers with any method, either via the HTTP extension or by opening streams directly, the support of the various GET, POST, PUT and other verbs on the receiving side of HTTP requests is a bit more complicated.

Background
The HTTP 1.0 specification (RFC 1945) officially defined only the GET, HEAD and POST methods, leaving open the possibility of adding extension methods:
Method        = "GET"                    ; Section 8.1
              | "HEAD"                   ; Section 8.2
              | "POST"                   ; Section 8.3
              | extension-method
The specification of HTTP 1.1 (as its last 1999 incarnation RFC 2616) defines explicitly other methods:
Method         = "OPTIONS"                ; Section 9.2
               | "GET"                    ; Section 9.3
               | "HEAD"                   ; Section 9.4
               | "POST"                   ; Section 9.5
               | "PUT"                    ; Section 9.6
               | "DELETE"                 ; Section 9.7
               | "TRACE"                  ; Section 9.8
               | "CONNECT"                ; Section 9.9
               | extension-method
Of these methods, the more interesting ones due to their usage in RESTful applications are GET, POST, PUT and DELETE:
  • GET is a safe, idempotent method and it is used to retrieve a resource.
  • POST is considered a catch-all method nowadays, but its intent is defining a subordinate resource to the current one. For instance, posting to a blog resource may create a new post.
  • PUT is the analogue of GET used to send a resource to the HTTP server.
  • DELETE is the analogue of GET used to, of course, delete a particular resource.
Client support
GET and POST are the bread and butter of requests sent towards PHP applications. They are commonly generated directly by the browser. A GET request is generated by a link or a form with the specified method attribute set as get. A POST request instead is usually obtainable in native HTML 4 only with a form, which may contain also an enctype attribute to set the Content-Type header of the request (usually employed for the upload of files via POST method.)
Browsers often limit their support for HTTP request to these two, as the HTML specification does not define a standard mean to generate other type of requests on the client-side. We have a programmatical way of making asynchronous HTTP requests, Javascript, but it does not help either as it's limited by the implementor's capabilities.
Javascript libraries do not force particular restrictions of the allowed methods: we may send GET, POST, PUT or DELETE requests to an endpoint on the server, but via an XMLHttpRequest object (which is their standard back-end) the unsupported methods will be emulated via overloaded POST. This means a POST request will be produced with an additional parameter (which may be named _method or _requestType, depending on the particular library) that describes the actual method used in the client. You get to maintain the semantic of the request in the client code, though, and maybe in the future native support for PUT and DELETE request will be available.
There are ways to make a real PUT or DELETE request, and they usually require more complex infrastructure on the client, like Java applets or non-standard Javascript (which is not supported in the majority of browsers), or even not using a browser as the client, for instance using a web service acting as a client of another one.

Server support
But how can we detect the HTTP request method in a PHP script? For the common methods, such as GET and POST, the superglobal arrays $_GET and $_POST are always available and contain the request parameters. You may want to wrap them with an object-oriented interface, and note that in the case of files upload via POST you should also look at the $_FILES superglobal array.
For the other methods, the first thing to do is setting up your webserver with a directive that routes all the PUT requests to a single, dynamic entry point. In the case of Apache, this is described in the PHP manual as:
Script PUT /put.php
The pointed script simply has to read from the standard input the PUT request:
$putdata = fopen("php://input", "r");
file_get_contents() won't work here; welcome back to the world of CGI! :)
The manual and the user comments are also a valuable resource for common pitfalls in implementing this type of endpoints.
With regard to the DELETE requests, the same configuration is valid to route the requests to a single entry point. Then, it's a matter of identifying the right environment variables, which may vary depending on your HTTP server. Fortunately, PHP frameworks do most of the work, and you are free to programmatically implement different behaviors depending on the type of the request.

Tuesday, April 06, 2010

Graphical tips for the average coder

I am not a front-end guy and surely not a web designer, but I promised myself not to avoid amateurial graphical work on occasion. While doing photomontages and altering images such as photos and movie posters, I learned some basic techniques and I now take great advantage of the editor's tools. I want to share these insights with the average programmer, who like me has seldom used a graphics editor and is scared by design work.

Selection is underrated in the minds of us programmers. Rectangular, circular, magic wand selections and similar tools are very sophisticate and composable: addition, subtraction and inversion of selections are the norm in a graphic's workflow. Selecting the right part of an image is fundamental for rendering the effects you want to apply, such as brush strokes, gaussian blur or even a bucket fill, to the correct zone instead of spreading them all over the image.

Working at an high zoom level - from 200% to 300% - gives you the opportunity for fine surgery. I guess this is why graphic designers have giant monitors, besides for fitting all the toolbars from Photoshop or GIMP on a single virtual desktop. Even when having an enlarged main view, you can always open another small view at a realistic scale to always have a glance at the overall picture.

Layers are the bread and butter of image editing, and every decent editor lets you modify, show and merge them independently, and combining layers of different sizes and positions in a unique image. If you are a web developer, I'm sure you have worked with CSS and the box model, so the concept of layering won't be a novelty. I store graphical works in the XCF format, which is the GIMP native format akin of the widely known PSD: both allow layers to be kept separately instead of being rasterized together in a JPEG or PNG. The separation of XCF from JPEG or PNG can be think of as the equivalent of source code and binaries: when you start playing with the source code you are transforming from an user to a programmer.

Transparency, often in the form of an alpha channel, is the glue that allows the composition of rectangular layers. Technically speaking, the alpha channel occupies 8 of the 32 bit of the color space, so that every pixel can specify its red, green and blue content with a total of 24 bits, but also its transparency (or by converse its opacity) to the point of being completely invisible.

Finally, another tool I find very useful in my pixel-obsessed, mathematical weltanschauung of image editing is the guide and the automatic snap of selections and layers to them or to the image borders. I simply cannot produce a decent work without setting up guides to attach layers to. I have not a perfectly steady hand while moving a mouse, which is not a precision device, but the combination of zoom and snaps lets me work like I was playing with Lego bricks or with my good old classes and objects.

Monday, April 05, 2010

How I learned to stop worrying and love new words

Because of the subject of my Bachelor's degree thesis, I am currently busy learning more and more about Java technologies, in particular the OSGi specification and the frameworks that implement it.
In the past, I saw articles about OSGi passing in DZone's feeds, and never cared much about it. It's possible and desiderable to avoid contact with many technologies we are not considering for right now: somehow we have to limit the amount of new information in our self-improvement process to the actually useful fields.
However, the thesis subject (audio and video search) is interesting but it involves a large amount of Java technology, in particular a framework built on top of the OSGi model. Here comes the pain: I did not know what OSGi was at all. Instead of continue worrying about it, I decided to dive into OSGi and I'd like to recall my steps here so that you can decide to take a similar journey on an argument that you are required to know.

Step 1: Wikipedia
Wikipedia is the starting point of most of my researches, even if it is not 100% reliable as every community-crafted content is. Wikipedia took me from an empty word (OSGi) to a definition:
The OSGi framework is a module system and service platform for the Java programming language that implements a complete and dynamic component model, something that does not exist in standalone Java/VM environments.
Moreover, well-written Wikipedia articles have many internal links to related material, both in the page body and in the See also section. Every new term you encounter usually points to its own definition, a scenery that can lead to a tab explosion but also to deep knowledge.

Step 2: define concepts in your own terms
I quickly discovered that OSGi applications are composed of bundles. The bundle term is part of the Ubiquitous Language of OSGi, but I did not know an exact definition. When you are doing a panoramic of a technology, it's useful to start with a good approximation which uses already grasped concepts:
OSGi bundles are particula JARs which includes some metadata files along with the hyerarchically organized .class files that contain the bytecode. Bundles export or import Java packages they respectively provide or require.
This is an approximation, since JARs and bundles do not strictly overlap. But it is a good one and let me abstract away most of the bundle internal organization for a while.

Step 3: resources to learn more
  • Google is often the best friend of a developer (as the GIYF acronym correctly says.) You can look for tutorials, but also for particular frequently asked questions.
  • Books on the subject, particularly if they contain good code samples, are the best road to a deep understanding of the technology. However they may not be the right material if you're only looking for a crash course.
  • YouTube videos are instead highly distilled knowledge, and the equivalent of a crash course. A 1-hour long talk can teach you very much about the assumptions and the usage of a framework like OSGi without effort: you just need to listen to the speaker.
  • also a search on Wikimedia Commons will bring you a lot of diagrams about your preferred technology (example), used throughout all the Wikimedia Foundation wikis.
Step 4: practice
My first practising step was producing an OSGi bundle and deploying it in an OSGi framework. I've done it even before step 3 because I like to get a walking skeleton as soon as possible, but I've gone reviewing my code once I had learned a larger part of the theory. Getting a running example is always a confidence booster however, even if you are copying much of the code without knowing its meaning.

The same learning process is going on for me for other material I'm using in the thesis, such as BPEL and the SMILA framework. While there may be aliens with genetic memories, you shouldn't be afraid of new concepts: everything you know was learnt at some point in your life.

Friday, April 02, 2010

Practical Php Patterns: Strategy

This post is part of the Practical Php Pattern series.

The pattern of the day (and of the week) is one of the most important ones in object-oriented programming: the Strategy pattern. Its intent is encapsulating an algorithm into a specific object, defining a clear input and output exposed to the Context where the Strategy is used, to let them both vary independently.
The Strategy used in a Context object can change for configuration purposes, thus allowing the selection of a specific behavior. Other use cases comprehend the tuning of non-functional requirements such as fast switching between performance or memory usage trade-offs of different algorithms that implement the same behavior (a classical example is sorting).
Finally, the use of Strategy objects simplify unit testing. For example, injecting in-memory Strategies instead of disk-related ones is the standard way to test classes that depend on infrastructure.
Participants
  • Context: uses a Strategy object, outsourcing part of its behavior.
  • Strategy: contract that Context sees.
  • ConcreteStrategy: implementation of Strategy as a particular behavior.
Switch statements or if-else chains are candidates for refactoring to a Strategy pattern (as they are for the State pattern). The difference between the two is their intent: State encapsulates data and possibly the transition to other States; a Strategy object usually does not produce other Strategy implementations and hides complex behavior.
The implementation of the Strategy pattern usually follows the classical composition paradigm: Context has a private field reference to a Strategy, while Strategy may be shareable as a Flyweight if the Context passes to it the necessary parameters (or even itself) when calling its methods.
The composition of a Strategy object is a valuable alternative to inheritance: in my opinion Strategy can be think of as a generalization of many patterns that gain their power from favoring composition. An Abstract Factory is in fact a Strategy dedicated to the creation of objects; an Adapter allow retrofitting an object as a Strategy for another one; and so on.

The code sample uses hidden Strategy objects for the sorting process of a Collection, in particular for comparing two values.
<?php
/**
 * The Strategy. Defines a behavior for comparing two objects
 * of the Collection.
 */
interface Comparator
{
    /**
     * @return integer  -1 if $a should precede $b
     *                  1 if $b should precede $a
     *                  0 if considered equal
     */
    public function compare($a, $b);
}

/**
 * The Context where the Strategy is employed.
 * Strategy is stored as a private field which can
 * be initialized only one time.
 */
class Collection implements Countable
{
    private $_elements;
    private $_comparator;

    public function __construct(array $elements = array())
    {
        $this->_elements = $elements;
    }

    public function initComparator(Comparator $comparator)
    {
        if (isset($this->_comparator)) {
            throw new Exception("A Comparator is already present.");
        }
        $this->_comparator = $comparator;
    }

    public function sort()
    {
        $callback = array($this->_comparator, 'compare');
        uasort($this->_elements, $callback);
    }

    /**
     * A representation for a clear output.
     */
    public function __toString()
    {
        $elements = array();
        foreach ($this->_elements as $value) {
            if (is_array($value)) {
                $value = 'Array with ' . count($value) . ' elements';
            }
            $elements[] = $value;
        }
        return '(' . implode(', ', $elements) . ')';
    }

    public function count()
    {
        return count($this->_elements);
    }
}

/**
 * A ConcreteStrategy that compares via the native operator.
 */
class NumericComparator implements Comparator
{
    public function compare($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return $a < $b ? -1 : 1;
    }
}

/**
 * A ConcreteStrategy that compares via the result
 * of the count() function.
 */
class CountableObjectComparator implements Comparator
{
    public function compare($a, $b)
    {
        if (count($a) == count($b)) {
            return 0;
        }
        return count($a) < count($b) ? -1 : 1;
    }
}

// ordering numbers
$numbers = new Collection(array(4, 6, 1, 7, 3));
$numbers->initComparator(new NumericComparator);
$numbers->sort();
echo $numbers, "\n";

// ordering Countable objects
$first = array(1, 2, 3);
$second = array(1, 2, 3, 4);
$third = new Collection(array(1, 2, 3, 4, 5));
$objects = new Collection(array($third, $second, $first));
$objects->initComparator(new CountableObjectComparator);
$objects->sort();
echo $objects, "\n";

Thursday, April 01, 2010

PHP 6 finally released

The versioning process of PHP has been exceptionally modified to clear the situation about the long-expected PHP 6. The last stable release, PHP 5.3.2, has been transformed in PHP 6 using the powerful Unix-based tool sed and finally released as PHP 6.0.

The goals of this new major release are multiple: the first is simply to set in stone, once and for all, the features included in PHP 6, regarding for example the Unicode implementation. To avoid conflicts within the development team, which were dividing the volunteers in groups that advocated different solutions, the encoding used to store string will be the UTF-1, where the 1 stands for 1K, the size of the standard bitmap-based characther glyphs which are strung together to compose the source code of PHP 6 scripts. No more question marks (?) will be displayed due to character set issues, at least while reading PHP source code.
The principal IDEs with PHP support, like Eclipse PDT and Zend Studio, have already announced the upgrade of their principal tools to simplify the editing process in the next days. This is probably the final death of the ugly old-style text editors like Vim which plagued the hardware vendors for years, delaying the adoption of new workstations needed to run the IDEs.
Though, the selection of the font to use in the set of glyphs is being discussed in the developers mailing list, along with the standard size, which must be readable even by PHP developers with an imperfect sense of sight.

A second, important objective is to finally give dignity to the large set of PHP 6 books released in the last three years. By re-releasing PHP 5.3 as PHP 6, there is finally the possibility of reading these books without wondering what PHP 6 is, or if the real release of PHP 6 has brought to the public different features from the one described in a Professional PHP 6 book. Now the books' publishers can state to have said the truth all the time about PHP 6 and its namespace and anonymous functions support, with the notable exclusion of the little transition from a character-oriented programming language to an image-oriented one.

To give you a picture (no pun intended) of this radical solution that has solved the Unicode support and the blog posts syntax highligthing problems in a single shot, I will include here the source code for an hello world program written in PHP 6.
Save the file and run php6 hello-world-php6.png to see PHP 6 at work.
Here is a sample from my Ubuntu terminal:
Note that PHP 6 added a ! and a new line, which were inferred from my enthusiasm in building and running it.

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