Archive for the 'Factory Method' Category

Bulgaria PHP Group: Introduction to Design Patterns

freedomIntroduction to Design Patterns. On Saturday, February 13 from 4:30-??? EST (New York time and 10:00-13:00 EET UTC 9:00-12:00) I will be making a presentation to the Bulgarian PHP Group via Google Hangouts. If you are unfamiliar with PHP 7, click on the picture of Vasil Levski, and download the special Bulgarian Edition! of PHP 7 & MySQL: An Object Oriented Introduction that I’ve been writing. (Only the first 6 chapters have been converted to PHP 7, and once the rest of the book is finished, all of it will be PHP 7 content and examples.) I only copied a few phrases from English to Bulgarian; so the book is written in English. (About 200+ pages currently.)

In case there’s a problem with Google Hangouts, I’ll have a streaming video of the talk available and communicate with the group via Twitter and/or email during the time of the talk. If you are not familiar with OOP, take a look at the first two chapters of PHP 7 & MySQL: An Object Oriented Introduction. Page 14 has a simple, clear and accurate definition of OOP that differentiates it from sequential and procedural programming.

Hope to see you via Google Hangouts on Saturday, February 13 at the Bulgaria PHP Meeting!

Factory Method with Return Typing

factorymethodIf you do a Google search for “Factory Design Pattern,” thankfully, the first hits are “Factory Method….,” the correct name of the pattern that Gamma and his associates developed as a fundamental design pattern. I am not at all impressed by nit-pickers, and lest you think me petty by touching upon the notion of “Factory” vs. “Factory Method,” I hope this post will show you why including a factory method in a Factory Method design pattern is both important and necessary.

The Factory Method: Abstract with Concrete Operations

Some of the posts about the Factory Method are more about the idea of a factory than a method within the Creator (Factory) interface. What the key is, though, is to design an interface in the Factory with both abstract and concrete elements which return a concrete Product. The details of the factoryMethod() are left up to the concrete implementations to decide which one to implement. The factoryMethod() is abstract, but with PHP7, we can establish a return type. What is a return type? When stated, it is the type of data that a method must return. In earlier versions of PHP, using type hinting, only certain types of objects could be included in a method’s arguments. Now, though, you can add a return type to a method. For example, the factoryMethod() in this example includes an IProduct return type after the closing parenthesis in the function declaration:

   abstract protected function factoryMethod():IProduct;

Like the scalar variables discussed in a pervious post that could be typed as code hints in parameters, a return value of a scalar variable such as a string means the that the method must return a string, as you can see in the IProduct implementations. However, the factoryMethod is designed to return an instance of an IProduct (the object) implementation. While common in other languages, return types are newly added feature in PHP7.

The Elegance of the Factory Method

Every time I go over the original Design Patterns in the GoF book, I find something new. One of my favorite patterns is the Template Method. The method itself is concrete but the operations within the method are abstract. The Factory Method is the opposite. The factory method is abstract, but it is called by a concrete operation defined in the interface. (I use the term interface to reference both PHP interface type classes as well as abstract class types.) To be sure, The Gang of Four, have more than a single implementation suggested for the Factory Method pattern, but in the class diagram, the method is set up in the interface (Creator) as an abstract method along with a concrete method as shown in Figure 1:

Figure 1: Factory Method class diagram

Figure 1: Factory Method class diagram

Before continuing, run the program (Play) and download the source code (Download.) The program is one I’m using to build a path from Lambda Calculus to PHP. (To run the downloaded source files, you’ll need PHP 7.)

PlayDownload

Once you have the source code downloaded and a sense of what the program produces, you’ll better understand how the Factory Method pattern makes it easy to update the “products” showing the lambda calculus and the PHP program using functional methods. The Creator participant in this pattern (IFactory) includes two methods; one abstract and one concrete as shown in the following listing:

< ?php
abstract class IFactory
{
    //This class is the 'Creator' interface in the class diagram.
 
    protected $productNow;
 
    /*
     * Factory Method--returns concrete Product--reutrns any
     * implementation of IProduct--it programs to the Interface
    */
 
    abstract protected function factoryMethod():IProduct;
 
    /*
     * The createProduct() is identified as 'anOperation()' in the class digram
     * While it is a concrete method, it returns the factoryMethod()
     * an abstract method.
    */
 
    public function createProduct():IProduct
    { 
        return $this->factoryMethod();
    }
}
?>

The IFactory abstract class may appear to be both strange and broken. How can a concrete method (createProduct) return an abstract method (factoryMethod)? Far from being broken, it’s brilliant. It means that while the createProduct() must return a factoryMethod(), the factoryMethod() can be implemented any way the developer needs following the structure of the interface.

Thoughtful Structure and Easy Update

As a Creational type of design pattern, the Factory Method may have what some consider an unnecessarily fussy (and complex) structure to get a simple product. In this example, the product returns nothing but strings with some HTML embedded to display text messages. Wouldn’t it be just as effective and a lot easier to have a single object for each product using a single interface? Or even simpler, have a single class and just add a set of properties for each string? The answer to all of those questions is, Yes, of course. However, there’s a caveat: if your product is simple; so is the solution. In the examples on this blog, I’ve tried to clarify how to build different design patterns correctly and clearly. We were stuck with the following paradox:

The clearer a design pattern example, the less useful it appears to be.

So, while generating output from strings is no great shakes, the important point is to see how simple it is to make changes using the Factory Method pattern. For example, instead of generating strings, suppose each product requires calls to a MySql database, a jQuery-based mobile UI, and a JavaScript graphic handler (not jQuery). If you look at Figure 2, you can see how this implementation follows the class diagram in Figure 1. The HTML UI and CSS file call the Client:

Figure 1: Implementation of the Factory Method pattern

Figure 1: Implementation of the Factory Method pattern

Okay, that’s a bit more complex, but the real issue is how to have several such products generated by the same program, each needing regular (e.g., daily) update and changes for several such products. By having a Factory Method take care of all of the new creations (additions and changes), you can rest assured that as the program gets bigger,as long as you follow the rules in the design pattern (attend to the rules laid down in the interfaces), not only will it be easier to maintain, but it will be less prone to bugs.

The Factory: The Method Returns Help the Developer

In creating the examples using PHP7 and the new function return types, I kept running into errors as I attempted to return product instances. The errors indicated that I was returning strings instead of objects (product instances). Because of the return typing, I was able to find the errors and return the objects, which in turn returned the strings from the products. First, look at the IFactory implementations:

< ?php
class FactoryID extends IFactory
{
    protected function factoryMethod():IProduct
    {
        $this->productNow = new LambdaID();
        return $this->productNow;
    }
}
?>
 
< ?php
class FactoryApp extends IFactory
{  
    protected function factoryMethod():IProduct
    {
        $this->productNow = new LambdaApp();
        return $this->productNow;
    }  
}
?>
 
< ?php
class FactoryPythag extends IFactory
{  
    protected function factoryMethod():IProduct
    {
        $this->productNow = new LambdaPythag();
        return $this->productNow;
    }  
}
?>

As you can see each implementation of the factory interface differs only slightly. Each calls a different product implementation. Because the createProduct() method is concrete, it does not need further implementation—even though the method calls an abstract method. (Note: Please remember that each class is saved as the class name with the “.php” extension.)
Continue reading ‘Factory Method with Return Typing’

PHP OOP & Algorithms II: What to Use

algorithm2What Are the Guidelines?

Like just about everything else in computing, there’s a certain amount of empirical testing. More importantly, however, are the general principles derived by both empirical and mathematical calculations. In the first post on algorithms and OOP, you saw an example that showed how many operations were necessary to find “Waldo,” a name near the end of an array of over 1,000 elements. One used a straight up loop and the other a binary search algorithm. Both were pretty quick; in fact it was hard to tell the difference in speed, and without seeing the little dots, you would not have seen the number of iterations required in each algorithm. You also saw that quadratic algorithms grew at rates that can quickly reach a point where processing comes to a crawl.

A Table Guide

Table 1 is derived from the 4th Edition of Algorithms (2011, p. 187) by Robert Sedgewick and Kevin Wayne. I’ve summarized it further. (Examples in the book are all in Java.) It is a rough but useful guide, and I have found it handy for a quick look-up.

Table 1: Algorithm Order of Growth

Name Order of Growth Description Example
 constant  1 statement    2 + 7
 logarithmic  log N divide in half    binary search
 linear  N loop    find max
 linearithmic  N log N divide & conquer    mergesort
quadratic  N² double loop    check all pairs
cubic  N³ triple loop    check all triples
exponential 2N exhaustive search    check all subsets

Fortunately, most of the time our algorithms are pretty simple statements, single loops or recursive calls. All of the models in green are algorithms we should try and stick with. You should avoid the reds ones if possible.

What About Recursive Algorithms?

Those who love to profess a little knowledge like to say that recursion is slower than a loop. As indicated, we really don’t want to end up paying attention to small costs. Recursion is important, and using recursive algorithms is cost effective, especially since the difference in running time is negligible.

We often use recursive implementations of methods because they can lead to compact, elegant code that is easier to understand than a corresponding implementation that does not use recursion.
~Robert Sedgewick and Kevin Wayne

(A recursive example of a logarithmic algorithm is not included here, but you can find a recursive binary search in the post on binary searches.) What we need to pay attention to are the order-of-growth issues. For example, quadratic algorithms on the lower end of the scale are not really that bad, but when the N increases at a squaring rate, it’s easy to run into problems. So if you avoid quadratic algorithms, you’ll be better off when the N increases. On the other hand, whether you’re using a recursive method for a binary search, you’ll not see that much of a difference as the N increases compared to non-recursive methods.

A Strategy Design Pattern Handles Algorithms

This blog has lots of posts detailing the Strategy design patterns; so if you’re not familiar with a PHP implementation of the Strategy pattern, you might want to take a quick look at the code. To get started, play the example and download the code.
PlayDownload

In the last post on algorithms, the program used a Factory Method pattern to produce an array, and in this post, the same pattern is used and two additional array products have been added. However, instead of having the algorithm classes be more or less on their own, all of the algorithm classes have been organized into a Strategy design pattern. Figure 1 is a file diagram of the objects in the application:

Figure 1: Object groupings with Strategy and Factory Method patterns

Figure 1: Object groupings with Strategy and Factory Method patterns

If Figure 1 looks a bit daunting, it is only three object groupings. The HTML and PHP Client make a request for one of seven algorithm implementations through a Strategy pattern. The concrete strategy implementations all get their data from a “data factory.” Figure 2 provides an easier (and more accurate) way to understand what’s going on.

Figure 2: Overview of the main purposes of the objects.

Figure 2: Overview of the main purposes of the objects.

So instead of having a complex task, you only have three groupings of classes and interfaces: Those making a request (Clients), those executing operations on data (Algorithms) organized as a Strategy pattern and the data itself organized with a Factory Method (Data.)

Figure 2 shows a simplified version of what the program does. The Context class considerably eases the requesting process. The HTML UI passes the name of the requested concrete strategy to the Client, and the Client uses the name as a parameter in a Context method. The Client is not bound to any of the concrete strategies because the strategy classes are handled by a Context object and method. (Click continue to see the PHP implementations of the algorithms.)
Continue reading ‘PHP OOP & Algorithms II: What to Use’

PHP OOP & Algorithms I: An Introduction

quadAvoiding the Misinformed

Programmers often spend more time un-doing bad information than using good information. One of the comments that set me off recently was someone “explaining” to others on a blog why PHP was not an object oriented language. Then he continued to blather on about the difference between compiled and interpreted languages. Whether or not a language is compiled or not has nothing to do with whether or not it is an object oriented language. Having interfaces, classes and communication between objects are the key criteria of an OOP language, and certainly since PHP5 has been a full-fledged OOP language. (We PHPers should not feel singled out because I recently saw post where a Java programmer pronounced that neither Python nor Perl were OOP, and she was “informed” otherwise by irate Python programmers. Perl has been OOP since V5.) So here I am again wasting time grumbling about people who don’t know what they’re talking about.

Instead of frothing at the mouth over the misinformed, I decided to spent more time with the well-informed. To renew my acquaintance with algorithms I began reading Algorithms 4th Ed. (2011) by Sedgewick and Wayne. Quickly, I learned some very basic truths about algorithms that had been only vaguely floating around in my head. First and foremost are the following:

Bad programmers worry about the code.
Good programmers worry about data structures and their relationships.
Linus Torvalds (Creator of Linux)

Since we’ve been spending time on this blog acting like good programmers, that was reassuring. In this post, I’d like to look at two things that are important for developing algorithms: 1) What to count as a “cost” in developing algorithms, and 2) Identifying good and bad algorithmic models. First, though, play and download the example. Using two different algorithms, a logarithmic and a linear (both pretty good ones), I’ve added “dots” to loop iterations to visually demonstrate the difference between a logarithmic algorithm (binary search) and a linear algorithm (loop). The “expense” of the algorithm can be seen in the number of dots generated.
PlayDownload

The example is a pretty simple one. However, since this blog is about PHP Design Patterns, I added a little Factory Method. The two algorithm classes act like clients making requests through the factory for a big string array with over 1,000 first names. Figure 1 shows the file diagram:

Figure 1: File diagram for use of Factory Method by two algorithm clients.

Figure 1: File diagram for use of Factory Method by two algorithm clients.

In looking at the file diagram, you may be thinking, “Why didn’t you use a Strategy pattern coupled with that Factory Method?” I thought about it, but then decided you could do it yourself. (Why should I have all the fun?)

Lesson 1: Leave the Bag of Pennies

The first lesson I learned in Bank Robbery 101 was to leave the bag of pennies. They’re just not worth it. Speed is everything in a bank robbery, and so you pay attention to how to get the most with the least time. The same thing applies to analyzing algorithms. For example, an object (as compared to an integer, boolean or string) has an overhead of 16 bytes. I have actually seen posts intoning, “objects are expensive…” Just to be clear,

Objects are not expensive. Iterations are expensive, quadratic algorithms are expensive.

In evaluating an algorithm you need to see how many operations must be completed or the size and nature of the N. An N made of up strings is different than an N made up of Booleans or integers. A quadratic (N²) and cubic (N³) algorithm are among the worst. They’re gobbling up kilo- or megabytes, and so that 16 bytes seems pretty silly to worry about. So instead of seeing an algorithm weight expressed as N² + 84 bytes, you’ll just see it expressed as ~N². (When you see a ~ (tilde) in an algorithm, it denotes ‘approximately.’) Another way of understanding the ~ is to note, They left the bag of pennies.

Lesson 2: Watch out for Nested Loops; they’re Quadratic!

I’ve never liked nested loops, and while I admit that I’ve used them before, I just didn’t like them. They were hard to unwind and refactor, and they always seemed to put a hiccup in the run-time. Now I know why I don’t like them; they’re quadratic.

Quadratic algorithms have the following feature: When the N doubles, the running time increases fourfold.

An easy way to understand the problem with quadradics is to consider a simple matrix or table. Suppose you start with a table of 5 rows and 5 columns. You would create 5² cells—25 cells. Now if you double the number to 10, 10² cells = 100. That’s 4 x 25. Double that 10 to 20 and your have 20² or 400. A nested loop has that same quality as your N increases. If both your inner and outer loop N increases, you’re heading for a massive slowdown.

Algorithms, OOP and Design Patterns are Mutually Exclusive

An important fact to remember is that good algorithms do not guarantee good OOP. Likewise, good OOP does not mean good algorithms. Good algorithms make your code execute more efficiently and effectively. Good OOP makes your programs easier to reuse, update, share and change. Using them together is the ultimate goal of a great program.

PHP Recursion Using Factory Method: Programming to the Interface

recurCoverRecursion as Client

Previous posts on this blog discussed Recursion and the Factory Method design pattern. In working with a recursive object to traverse a list of strings or numbers (or any other objects for that matter), PHP developers typically target an array. In developing a simple recursive object, I realized that it made more sense to set up an another class for the array object. Why bind the process or creating and populating an array to the object designed to transverse it? After all, what if you wanted to use the object to traverse any list; not just the one bound to the recursion operation?

The Factory Method for Handling Array Objects

From the not-too-difficult decision to separate the array creation and population process from the transversal process, it was a pretty quick leap to using the Factory Method. That would give me plenty of flexibility, and I would be able to use the factory implementations to do different things with the products—like sort or filter them before returning them to the requesting client.

In this case, the requesting client would be the Recursion object.

The Client class triggers the appropriate method in the Recursion object to select whatever list is available. The selection process would be handled by an HTML UI. The class diagram is integrated into the application. Click the Play button below first to see the operation and class diagram and then the Download button to get all of the files:
PlayDownload

When you Play the program, notice in the class diagram that the Recursion class includes a method, getArray(Factory). This method is an example of programming to the interface and not the implementation. The method expects an argument that is a Factory child, but it can be any Factory implementation. The type hint is the Factory interface and so any implementation of Factory works fine. As a result, you can add as many different Factory implementations as you want without having to worry about a train wreck like you can get easily by programming to implementations.

The Recursion Class Makes use of the Factory

As noted at the outset, the Recursion object is set up to use any Factory implementation. In this example, only three implementations use the Factory interface. The factory method itself is makeArray(), but it’s left to the implementations how the array to be returned to the requester—the Recursion class. The PeopleFactory and PetsFactory sort the list in alphabetical order before returning it to the requesting client. However, the ToolsFactory uses a reverse sort so that the highest Wrench element is first and the Awl is last. The recursive iterator in the Recursion object could care less; it just transverses whatever list it gets from the Factory implementation and prints it to the screen.


class Recursion
{
    //The Recursion class is the Client
    //in making a request from the Factory
    private $members;
    private $counter=0;
    private $size;
 
    public function getPeople()
    {
        //Makes request to Factory child
        $factoryNow=new PeopleFactory();
        $this->getArray($factoryNow);
    }
 
    public function getTools()
    {
        //Makes request to Factory child
        $factoryNow=new ToolFactory();
        $this->getArray($factoryNow);
    }
 
    public function getPets()
    {
        //Makes request to Factory child
        $factoryNow=new PetsFactory();
        $this->getArray($factoryNow);
    }
 
    //By programming to the interface (Factory)
    //you can use different implementations
    private function getArray(Factory $factoryBuild)
    {
        $this->members=$factoryBuild->makeArray();
        $this->size=count($this->members)-1;
        $this->recursive();
    }
 
    private function recursive()
    {  
        if($this->counter <= $this->size)
        {
            echo "" . $this->members[$this->counter] . "
"
; ++$this->counter; return $this->recursive(); } } } ?>

As you can see, the recursive() method is pretty simple. It just keeps using echo to send the current element value to the screen, increments the counter by 1, and then if it hasn’t exceeded the length of the array, it calls itself to repeat the process. The Factory implementations already took care of the sorting arrangements–or anything else developers want the Factory implementations to do.

Each of the 3 public “getter” methods call the private getArray(Factory) method using a Factory implementation as an argument. The passed argument calls the factory method (makeArray()) to get the requested array which is stored in the $members property. Finally, getArray(Factory) calls the recursive() iteration method that traverses the $members property containing the array.

A Lot of Work for Iteration

If you’re thinking

…that’s a lot of work for a simple operation (displaying sorted lists on the screen)

I’d not disagree. The point of design patterns, though, is re-use on a much larger scale. As projects get bigger and bigger, you need tools to deal with them. The good news is that if you can use them on a small scale like the examples on this blog and in Learning PHP Design Patterns, you’re prepared to work on larger projects involving teams of programmers and some seriously good applications.