Design Patterns Made Easy – Factory Pattern

Factory Pattern

Factory Pattern helps to instantiate complex objects keeping future changes in mind. In this case, you don’t use the new keyword to directly instantiate an object of a class, but use a static method of another factory class. This helps to wrap up complex and dynamic construction of objects or helps in cases where the right class to instantiate depends on input parameters.


class Person {
	private $name;
	protected $type;

	function __construct($_name, $_type) {
		$this->name = $_name;
		$this->type = $_type;
	}
}

interface iPerson {
	function behave();
}

class Good_Person extends Person implements iPerson {
	protected $type;

	function __construct($_name) {
		$this->name = $_name;
		$this->type = "GOOD";
	}

	function behave() {
		echo $this->name." is a ".$this->type." person!";
	}
}

class Bad_Person extends Person implements iPerson {
	protected $type;

	function __construct($_name) {
		$this->name = $_name;
		$this->type = "BAD";
	}

	function behave() {
		echo $this->name." is a ".$this->type." person!";
	}
}

class PersonFactory {
	function create($name, $type) {
		$type = ucwords(strtolower($type));
		$class = $type."_Person";
		if (class_exists($class)) {
			return new $class($name);
		} else {
			throw new Exception("Invalid type");
		} 
	}
}

$type_of_person = "GOOD"; //This could be $_POST['person_type']
$good_person = PersonFactory::create("Floyd", $type_of_person);
$good_person->behave();

Now the construction logic has been separated to the Factory class and therefore the code is much more flexible and maintainable in the long run. If the logic behind instantiating the object changes at some point, all we need to do is update the factory create method and leave the rest of the code as they were.

Design Patterns Made Easy – Revisit OOP Concepts

This is the first article in a series with objective to make design patterns understandable to everybody having basic OOP concepts. With so many different languages, frameworks available and emerging every now and then, its very important to have mastered the fundamentals of good programming practices than trying to work out every new language or frameworks. Design Patterns help you to tackle common architectural issues and encourage best practices to provide long term manageability to your application. This series assume you have basic understanding of OOP concenpts i.e class, object, inheritance, scope, interface etc. Don’t worry if you can’t remember all of them, we will revisit some of these in this article, specially those important for understanding the design patterns.

If you’d like to see all the articles in this series, please click here.

Visibility

Visibility of a property or method can be defined as public, private or protected. It defaults to public.

Public

This makes a property or method available from anywhere, within the class, derived objects and extended classes.

Private

This makes a property or method available from only within the class. Derived objects will not have access to these properties or methods directly but can use public getters (will be explained later) to gain indirect access.

Protected

This makes a property or method available from within the class or any class which extends it.


class Person {
  public $name;
  public $age;
  protected $type;
  private $id;

  //Constructor that receives the name, age, type and sets the object properties
  public function __construct($_name, $_age, $_type) {
    $this->name = $_name;
    $this->age = $_age;
    $this->type = $_type;
    $this->id = uniqid();
  }

  //Getter for $type
  public function getType() {
    return $this->type;
  }

  //Getter for $id
  public function getID() {
    return $this->id;
  }
}

class Student extends Person {
  public $student_id;

  //We can redeclare private and protected properties, but not private
  protected $type;

  public function __construct($_name, $_age, $_type) {
    $this->name = $_name;
    $this->age = $_age;
    $this->type = $_type;
  }
}

$person = new Person("Floyd", "28", "PERSON");

//Will display Fatal Error: Cannot access private property Person::$id
//echo $person->id;

//Will display Fatal error: Cannot access protected property Person::$type
//echo $person->type;

//Will display something like 55123095e0161
echo $person->getID();

$student = new Student("Floyd", "28", "STUDENT");

//Will display STUDENT
echo $student->getType();

Static

If a property or a method of a class has been declared static, this means, this property or method can be accessed without initializing an object of that class. Please note that $this is not available since there is no object instantiated. Instead Scope Resolution operator (::) has to be used.


class Utility {
  public static $last_result;
  public static function add($num_array, $append = false) {
    if ($append) {
      self::$last_result += array_sum($num_array);
    } else {
      self::$last_result = array_sum($num_array);
    }
    return self::$last_result;
  }
}

//Will display 15
echo Utility::add([1, 2, 3, 4, 5]);

//Will display 30
echo Utility::add([1, 2, 3, 4, 5], true);

Utility::add([1, 2, 3], false);

//Will display 6
echo Utility::$last_result;

Interface and Abstract classes

Interface

An interface is a facade for a class. It is a blue-print which dictates how the class will look like. Interfaces can not be instantiated and must be implemented. Interfaces do not define the behaviors but defines what those behaviors are. You must implement your own behaviors by implementing interfaces in a class.


//Interface IPerson defines what a Person class can do
interface IPerson {
  public function eat($food);
  public function sleep($hours);
  public function walk($miles);
}

class Person implements IPerson {
  private $name;

  public function __construct($_name) {
    $this->name = $_name;
  }

  //Person class must define the behaviors mentioned in IPerson interface i.e eat(), sleep() and walk()
  public function eat($food) {
    echo $this->name." eats ".$food.".
";
  }

  public function sleep($hours) {
    echo $this->name." sleeps for ".$hours." hours.
";
  }

  public function walk($miles) {
    echo $this->name." walks ".$miles." miles everyday!
";
  }
}

$person = new Person("Floyd");
$person->eat("Pizza");
$person->sleep(6);
$person->walk(5);

//Output:
//Floyd eats Pizza.
//Floyd sleeps for 6 hours.
//Floyd walks 5 miles everyday!

Abstract Class

Abstract classes can not be instantiated but can be extended. It can contain empty methods as well as well defined methods if you’d like all the classes that extends it to have some common behaviors. Lets take a look at the above exmaple re-written with Abstract class instead of an Interface.


abstract class Person {
  //Scope changed from private to protected to allow access from child classes
  protected $name;

  public function __construct($_name) {
    $this->name = $_name;
  }

  public function eat($food) {
    echo $this->name." eats ".$food.".";
  }

  public function sleep($hours) {
    echo $this->name." sleeps for ".$hours." hours.";
  }

  public function walk($miles) {
    echo $this->name." walks ".$miles." miles everyday!";
  }
}

class GoodPerson extends Person {
  //All classes which extend Person will have default eat(), sleep() and walk() methods.
  //Lets define a donate() method in addition
  public function donate($money) {
    echo $this->name." donates ".$money."$ to charity!";
  }
}

//Will show Fatal error: Cannot instantiate abstract class Person
//$person = new Person();

$person = new GoodPerson("Floyd");
$person->eat("Pizza");
$person->sleep(6);
$person->walk(5);
$person->donate(10);

//Output:
//Floyd eats Pizza.
//Floyd sleeps for 6 hours.
//Floyd walks 5 miles everyday!
//Floyd donates 10$ to charity!

That’s it for today. In the next post I will start explaining the most important Design Patterns one by one. Keep in touch! If you have any question or suggestion, please comment below.

Next Article: Factory Pattern

Build idiot proof systems!

Few days ago, I was asked to evaluate a few possibilities for a new project. I wanted to check the Jetpack plugin but we/I did not have any WordPress installation in any of our/my servers. In order to save time, I directly came to this site and tried to install Jetpack 1.9. It did not let me because I was using an older version of WordPress, probably 3.5.2. I was in hurry, so I downloaded a backup utility with a good rating, XCloner and took a full backup. Despite all those “verify your backup before you proceed” warnings, I tried to update to the newer version directly.

As you’ve guessed, my site went down half way through the update! Not to worry, I was smart, I took a backup! I started googling how to restore a XCloner backup. It seemed more complex than I had anticipated, but was not rocket-science. I started the restore process but it came back with a warning in red lines, my extracted files did not have the expected file sizes. This is when it strike me that I was an ass not to take a proper backup and verify it. I probably lost all of my articles. I am a lazy man. It took me one year to motivate myself for a personal blog, one more year to set it up and one more year to actually start writing! I am not the type to not lose faith and start over. So I mentally prepared myself for the worst. I was feeling like an idiot!

When I came back from office, I started to dig down.  I looked at the source files on my server. There was a lot of files showing zero bytes. I looked at the XCloner backup files and database script. There were only a few files, I must have done something wrong while setting up the backup. Also, the database script was broken half way through a INSERT script, a lot of tables were missing. In summary, the backup wasn’t usable at all.

I decided to delete everything and go for a fresh installation. I downloaded the latest version of WordPress. While downloading, I noticed that there is a process for manual upgrade. I also noticed that its not very uncommon for people to crash their site during version upgrades and then they have to switch to manual upgrade. I started with finding all the files with zero byte size, and replace them with the files from the downloaded distro. To my greatest surprise, the site started showing up! Well, not all of it, but I could read the articles and see the pictures, at least some of it, but I could not use the backend. The UI was broken, the site was missing CSS styles, the scripts were not working. Firebug console was full of warnings and errors. So, instead of replacing only some files, according to the WordPress manual upgrade guide, I decided to replace all files except wp-config.php, .htaccess and wp-contents folder from the downloaded archive of the new WordPress 3.8.2. After copying everything, I tried to log into the backend again. It automatically took me to the database upgrade screen. This time, I performed a mysql backup from cpanel before upgrading it, but the upgrade was smooth. My site was back, up and running in less than an hour!

I was awestruck by the simplicity of the upgrade process. As a developer, there are times when you hate the users but you should also expect them to make very unusual mistakes. When they cause disasters even after being instructed specifically on how to avoid it, they will come to you and at the end of the day you should be able to find a way around. Just because you told them not to push that red button does not mean somebody will not push it. May be it was accidental, may be he was in a bad mood, may be something else happened but your system should be solid enough to handle catastrophes. Deleting a file or a record, power failure during a transaction, changing a password and not remembering it, the list goes on and on. We are sitting on a world of automated systems where for every system, multiple automation options exist. These small idiot handling will make your system come on top of another. No matter how good your system is, if its not idiot proof, its simply not good enough.

How to estimate a project very fast!

Yesterday, my boss called me around noon. He told me that he’ll be working from home in the afternoon as he had a client call to attend. Also, he has received a new project proposal from a client who wants to clone a very famous website, for which I need to provide a rough/ballpark estimate. Usually for big projects, he works directly with me in preparing the estimates, but this time I will have to do it alone. On top of that, I have less than three hours.

I am sure, some of us have to face this scenario often. You don’t need to do an accurate estimate, yet you can not go off by big margins. You don’t get much time to evaluate and list every details, you don’t even get to play around with the system. In such cases, the ideal approach, we not exactly ideal, but it worked for me so far, is to:

1. Isolate the features. As many of them you can, obviously without missing the major features. If its a web project, it might have several back-ends for users of different roles. List those features as well. First take a notepad or an excel file and keep listing features as you go through the URS/FS documents or sample website. Don’t waste too much time to layout every details, but try to put the feature in a single line. For example: you should write “Save/Update user’s location data after every successful login” instead of “When a user logs in, save his location information in the system. If a location is already available, overwrite it.”

2. Separate and list the UI elements and page designs. Most of the well designed projects often has reusable UI components or design blocks. Use your common sense to roughly guess how much of the work can be reused.

3. Beside every feature or UI elements, make two columns: Min hours and Max hours. Think how much time the feature would likely take to develop. Whatever you think is fair, make the Min hours ~20% less than that and the Max hour ~40% more. For example: If you think a feature would take 16 hours to develop, put 12 hours in Min and 22 hours in Max. Please note that, for some of the items, the hours are very obvious and kind of standard. In such cases make the Min and Max as close as possible, or better, avoid the Min, put the exact amount in the Max column.

Estimate a project

Estimating a project

4. Don’t forget to include some standard items i.e Initial Analysis, Database Development, Product Research, Documentation, Testing, Deployment, Client Communication etc. All these items makes up a complete project. If you forget to mention these, you’ll regret it later.

5. In addition to all these, I personally add another item “Contingency” which is a flat 10% of the Min and Max hours columns, often calculated by a formula and rounded to full numbers. This items gives you a little peace of mind which is often prove to be a life saver during the end days of the project. If you’re one of those guys who estimates a project very tight, make sure you add the contingency period. Your developers will thank you for this.

Thats all I can remember right now. How do you estimate your projects? Feel free to share with me.

Feel something is wrong? Something probably is!

Today I had faced a near disaster. We were to deliver an offline HTML/CSS/JS based web application which was planned for distribution in a major Arab-African event using USB drives. The application itself was pretty straight forward, we had to export and stage data, implement a JSON provider, convert those exported data to JSON and use it inside our application using AJAX calls. Even though the project was small, we had a commitment and a very rigid deadline. There was another company who were waiting for us to provide the files for them to prepare and deliver the USB for the event. I had a junior colleague working with me. For the sake of visibility, we placed the development version of the application in his local apache server and also on our demo server. The project ended very quickly with almost no hiccups. Not even the smallest ones! I was very happy to see it progressing rapidly. But, at the same time I had something in my head telling me something is wrong. The project was too small for me to get worried. We tested the application in different browsers for compatibility and then delivered on schedule. The client was more than happy.

Three days after, the company who were responsible for the USB came back to us with some questions. I was not in the office, so my project manager downloaded the contents which we had sent them earlier and KABOOM! It was not working! Well, it was working with Firefox, but not with Chrome or Internet Explorer. By this time, they must have prepared the USB cards and shipped them to our client! We were at loss!

The problem was in making AJAX calls to local JSON. Both Chrome and Internet Explorer were treating the AJAX calls to the local JSON files as cross-domain calls and it was failing. I quickly got panicked and could not think of a way to make the AJAX calls domain safe without taking the whole thing apart. This glitch got overlooked since were were testing the whole thing from a local apache server and the JSON file was on the same domain (localhost) as the HTML file. I did check the files directly from the file system, but using only Firefox (which was my default browser) and things worked flawlessly. It never occurred to me to check the files from the file system using different browsers since we had them tested in different browsers earlier from our apache servers, both development and demo!

The solution was very simple. Since all those JSON content were static, we just had to copy those into a javascript variable and use it from there instead of making AJAX calls to get them from the file system. We changed it very quickly and made a second delivery. By this time, my PM had called the USB provider and made sure they did not go for mass production yet. So, in the end, this whole thing did not cost us anything, other than sweat and panic!

The thing is, I was not comfortable while delivering the contents the first time but I did not care to recheck the files thoroughly and systematically. When you’re working in the industry for some time, you actually grow a sixth sense which tells you if something is about to go wrong. Do not ignore these feelings, make sure you’re absolutely confident while delivering. If you feel something might be wrong, chances are high that something is wrong! Trust your instinct, it never hurts to invest an extra hour double checking if everything is behaving as they should.

Autorun HTML file from a CD-ROM

I recently came across an interesting project which required to open an HTML file inside the CD-ROM using the default browser on the users side. There are two ways, both are equal in terms of complexity and flexibility.

Method 01:
This uses the standard ShellExecute command.


[autorun]
shellexecute=index.html
label=Autorun HTML
action=Open index.html

Method 02:
This method requires you to download a small executable and put it within the contents.


[autorun]
open=autorun.exe index.html
label=Autorun HTML
action=Open index.html

Please note that the above examples only shows a few of the options you can use in a Autorun.inf file. For other possible entries, please refer to MSDN.

Developer vs Googler

So you google a lot while writing code or developing a piece of application and that makes you wonder whether you really are a good programmer or just a good googler? Lets find out.

This thought has been bugging me for the last few months since it seems like I cant really do anything without the help from the mighty ‘G’. Whether its a simple JavaScript String.ReplaceAll() method or a C# String.ReplaceFirst() method. Lets see what most of us (considering a developer of average skills) will come up with, without googling:


//C# ReplaceFirst(): Replaces the first occurrence of a given pattern with another
public string ReplaceFirst(string baseText, string toSearch, string toReplace) {
    int pos = baseText.IndexOf(toSearch);
    if (pos < 0) {
        return baseText;
    }
    return baseText.Substring(0, pos) + toReplace + baseText.Substring(pos + toSearch.Length);
}

//JavaScript ReplaceAll(): Replaces all instances of a given pattern from a string
function ReplaceAll(toSearch, toReplace, baseText) {
    while ( baseText.indexOf(toSearch) > -1) {
        baseText = baseText.replace(toSearch, toReplace);
    }
    return baseText;
}

Now, on first thought, my incapable mind did not event think about using RegularExpressions! If I were to google first, I could’ve done much better:


//C# ReplaceFirst(): Replaces the first occurrence of a given pattern with another
public string ReplaceFirst(string baseText, string toSearch, string toReplace) {
    var regex = new Regex(Regex.Escape(toSearch));
    return regex.Replace(baseText, toReplace, 1);
}

//JavaScript ReplaceAll(): Replaces all instances of a given pattern from a string
function ReplaceAll(toSearch, toReplace, baseText) {
    return baseText.replace(new RegExp(toSearch, 'g'), toReplace);
}

Now that you’re thinking I must be a noob to not think about using RegularExpressions on the first place, how about we try to do this without RegularExpressions but in a super cool way?


//JavaScript ReplaceAll(): Replaces all instances of a given pattern from a string
function ReplaceAll(toSearch, toReplace, baseText) {
    return baseText.split(toSearch).join(toReplace)
}

If I had googled first, I could see all these different implementations which I would be able to use in similar scenarios in future, not just this one. These solutions might not be bulletproof but will do the job for my particular need. Also, imagine the facial expression of the developer who gets to work on this after me seeing all these elegant solutions to otherwise very simple problems.

Googling is simply not about copying code out of peoples work but also to explore the possibilities. Technology has enabled us to share and teach what we know to others who wants to know. There is nothing wrong with a bit of researching before jumping into writing codes. You’ll be surprised to see what you could learn simply by studying other peoples code and suggestions. And not all of our problems are related to programming, we also need to trouble shoot server problems, network connectivity issues, code deployments etc. All these will keep throwing different challenges to you and its not heroic to try to solve all these without any help. If you have a senior colleague or a friend or a mentor who helps you whenever you’re stuck, google does the same for you. Its true that if you’re blindly copying the code and pasting without even understanding or studying the code, than this can not be any worse for you!

How could we make the most out of googling and improve our skills at the same time?

  • Study the solutions provided by others. Compare their solutions to what you had in mind.
  • Try to learn different ways to solve a problem. Do not stop at the first solution you get.
  • Use the knowledge you’ve gained to solve other problems of the same kind.
  • Avoid copying wherever possible. Get the idea, understand the algorithm but write your own code. Nothing beats the knowledge gained by doing it yourself even though you’ve borrowed the idea off someone else.
  • If you think you can do better, contribute to the community. Take your solution to them.
  • Even if you think you know the solution to a problem, studying always helps. With the always changing technologies, chances are you’ll find a better solution each time you look!

So folks, don’t worry about how you code as long as you get to learn something in the process. Its okay to not know something and its a lot better than knowing the wrong thing.

Check-In documents automatically after uploading to Sharepoint

For the last two days, we’ve been suffering from this problem where, we need the following features:

  • Support for Sharepoint library versioning
  • Documents need to be checked out before one can edit
  • Whenever a new document has been uploaded, it needs to be in checked-in state (we have a custom workflow which fires on document upload, it requires the document to be in checked-in state)

Now, if we disable the force checkout option from library settings, multiple persons can open and edit the same document, which obviously we don’t want. On the other hand, our workflow simply wont trigger on new document upload because the newly uploaded document remains checked-out. If we manually check-in the document, the workflow follows immediately. The bottom-line is, we need a post-upload event to check-in the uploaded document forcefully.

Sharepoint allows developers to create Event Receiver handlers which can be used to override sharepoint events on various levels. On this occasion, we need to override the ItemAdded method of Document Library. For this, we added a new Event Receiver item within our workflow project. Sandboxed mode was chosen for this purpose. From the Visual Studio wizard’s list of events, select An item was added from  List Item Events on Document Library. This will create a new class file with the ItemAdded method overridden. We just have to write our own code.


using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace CustomItemAdded.EventReceiver1
{
    public class EventReceiver1 : SPItemEventReceiver
    {
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           SPFile thisFile = properties.ListItem.File;

           if (!thisFile.CheckOutType.Equals(SPFile.SPCheckOutType.None))
           {
               thisFile.CheckIn("Checked in by custom event handler.");
           }
       }
    }
}

SOAP Calls using jQuery Ajax

Few days ago, I came across a situation where I had to get data from a .NET Web Service using jQuery Ajax. Here is a sample code:


var soapMessage =
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
        '<soap:Body>'+
            '<SomeMethod>'+
                '<Arg1>Arg1 Value</Arg1>'+
                '<Arg2>Arg2 Value</Arg2>'+
            '</SomeMethod>'+
        '</soap:Body>'+
    '</soap:Envelope>';

$.ajax({
    url: "http://localhost/someService.svc",
    type: "POST",
    dataType: "xml",
    contentType: "text/xml; charset=\"utf-8\"",
    headers: {
        SOAPAction: "http://localhost/someService/SomeMethod"
    },
    data: soapMessage,
    success: function(soapResponse){
        //DO SOMETHING
    }
});