Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Wednesday, August 28, 2013

Javascript Namespacing: Object Literal Namespace (OLN) in Javascript

Javascript, unlike many other programming languages does not come with its built-in namespace or class pattern. In many other languages such as Java or C#, the code comes with built-in name-spacing and class patterns. Have a look at C#'s namespace pattern below:
namespace Project
{
    class MyClass
    {

    }
}
You may first ask why do we need a namespace to begin with in a language like Javascript?! As a reply, one can simply say that namespaces avoid the global namespace of your application to become polluted by dividing the global namespace into several manageable chunks of code, calling one another. It is very obvious that if you are writing an application you cannot just continues writing it like this, can you?
var getUserInput = function () {

};

var thenSortIt = function() {

};
If you think you can, you are right! But then you lose track of your functions as it becomes so hard to find your functions in thousands of lines of code and newly added functions. Even if you divide them in separate script files, you still are polluting the global namespace, i.e. as the application starts, you are injecting all the code suddenly inside the browser in one big scope. Do you think that is desirable?! If so, think twice.

The Object Literal Namespace (OLN) pattern, comes with a very easy idea. Wrap your namespace inside a very big object literal:
var myNamespace = {
 instanceVariable: undefined,

 setter: function (element) {
  this.instanceVariable = element; 
 },

 getter: function() {
  return this.instanceVariable;
 },

 randomFunctions: function (message) {
  return "Hello, " + message;
 } 
};
In the following script, that is how you call and interact with you OLN in Javascript:
myNamespace.setter(1000); 

console.log(myNamespace.getter()); //Output: 1000

console.log(myNamespace.randomFunctions("Amir Rahnama!")); //Output: Hello, Amir Rahnama!
One fact to remember here, is that by using OLN as your namespace pattern, there is no level of information hiding in your namespace. You are exposing your whole namespace to the caller's code. Meaning that, you can replace the second line of above with the following line, keeping the output still the same:
console.log(myNamespace.instanceVariable); //Output: 1000
Actually, that is one of the main reasons that many developer dislike OLN namespaces, because they believe in a namespace with public and private values at the same time.

One last thing to note is that you can dynamically extend your OLN Namespace by the following code:
//Dynamically add instance variables to myNamespace
myNamespace.newInstanceVariable = "I am new";

//Dynamically add newFunction to myNamespace
myNamespace.newFunction = function (newMessage) {
 return "Hello Again," + newMessage;
};

And you can guess that you can use them as soon as they are declared:

console.log(myNamespace.newInstanceVariable); //Output: I am new
console.log(myNamespace.newRandomFunction("Mr, Amir Rahnama!")); //Output: Hello Again, Mr. Amir Rahnama!

Friday, December 21, 2012

Abstract Factory Pattern in Java

I was searching the other day for this pattern and while there are many websites referring to the pattern, they mostly fall into long discussions of this pattern. What I will do is that I make it as brief as possible.
We all know that our desire for coding is to have full flexibility to change components without re-writing many parts of code. So in any service-oriented scenario, what we mainly trying to do is to keep the client "as dumb as possible". So let us cut right to it.

The minimum requirement for Abstract Factory Pattern is to have a client class, one interface and (at least) two classes that implement that interface. This means that those two have their methods in common. If that is not the case for you, you are looking at the wrong pattern. Abstract Factory Pattern needs to be applied to help you instantiate a group of similar classes. Like in our example, we have IT consultant and Software Developer classes:


public class ITConsultant implements EmployeeInterface {

    private final String name;

    public ITConsultant (final String name)
    {
        this.name = name;
    }

    @Override
    public void introduceYourself()
    {
        System.out.println("Hei, I am " + name + " and I am an IT Consultant, cool huh?");
    }

    public String getName() {
        return name;
    }
}
public class SoftwareDeveloper implements EmployeeInterface {

    private final String name;

    public SoftwareDeveloper (final String name)
    {
        this.name = name;
    }

    @Override
    public void introduceYourself()
    {
        System.out.println("Hei, I am " + name + " and I am a Software Developer, cool huh?");
    }

    public String getName() {
        return name;
    }

}
See how similar they are? Because they both are implementing the EmployeeInterface:
public interface EmployeeInterface {
    public void introduceYourself();
}
Before going to the last step, I just want to point that sometimes even thinking about this pattern, gives me the idea that some of my classes can really implement a single-interface. So thinking about design patterns make your mind up. Now, if the client wants to instantiate an instance of, for example ITConsultant class, you can simply do this:
public class BadPractice {
    public static void main(String [] args)
    {
        SoftwareDeveloper amir = new SoftwareDeveloper("Amir");
        amir.introduceYourself();
    }
}
Why bad practice? Because your client code is hard-coded with this class and changes make you to re-write this. Now is the time for Abstract Factory Pattern! This is an example of a factory class:
class EmployeeFactory {
    public static EmployeeInterface createEmployee(final String name, final String seed )
    {
        if (seed.equals("SWD"))
            return new SoftwareDeveloper(name);
        else if (seed.equals("ITC"))
            return new ITConsultant(name);
        else
            throw new IllegalArgumentException("Your seed is not compatible to any of classes");
    }
}
Notice that the method of the factory should be static. Also we pass name and a seed to the factory so that we can decide which type of instance to return. The name parameter will be passed as name for the constructor of SoftwareDeveloper and ITConsultant classes. Now the last part of the work is to create our dumbo client. Client does not know anything about the details and gets decoupled:
public class GoodPractice {

    public static void main(String [] args)
    {
        EmployeeInterface amir = EmployeeFactory.createEmployee("Amir", "SWD");
        amir.introduceYourself();
    }
}
The output is now:
Hei, I am Amir and I am a Software Developer, cool huh?
as we expected! And that was it.