animesh kumar

Running water never grows stale. Keep flowing!

Archive for May 2011

Fun with Singleton (Python, Javascript, Java)

leave a comment »

[tweetmeme source=”anismiles” only_single=false http://www.URL.com%5D

They say that Singletons, like global variables, are evil. They hide dependencies; are harder to test and even harder to extend. Singletons are lies, and it’s best to keep away from them. But, there are scenarios where you need them. For example, when you want a shared resource like printer spooler or file manager or log manager, you want a single object to handle requests from all the various parts of your application.

In this blog, I am going to explore various ways to make Singletons in languages like Python, Java and Javascript so as to keep it simple, elegant and usable. Let’s talk about Python first. I love it, and it’s a really really wonderful language, and in here, there are n different ways to solve a problem. Singletons are no exception. The most natural way to do it is to create a decorator.

class Singleton(object):
	def __init__(self, klass):
		self.klass = klass   # class which is being decorated
		self.instance = None  # instance of that class
	def __call__(self, *args, **kwargs):
		if self.instance is None:
			# new instance is created and stored for future use
			self.instance = self.klass(*args, **kwargs)
		return self.instance

Now, let’s say you have a Resource class. To make it singleton, you just need to decorate it with ‘@Singleton‘, and you are done.

@Singleton
class Resource(object):
	def __init__(self, klass):
		self.name = None

Cool…eh? There are other – nerdy – ways too. Python uses an internal dictionary ‘__dict__’ variable to keep track of an Object’s properties and methods. So, if you can share ‘__dict__‘ across multiple instances of a Class, you can share the state between them. And isn’t that Singleton? Yes, that is. You might have many many instances, but all of them behave exactly the same.

class Singleton(object):
	_shared = {}
	def __init__(self):
		self.__dict__ = Singleton._shared
class Resource(Singleton):
	def __init__(self, klass):
		self.name = None

Since ‘self.__dict__‘ now refers to ‘_shared‘ dictionary, all instances of Resource would use the same dictionary and hence they will all have the same behavior. Geeky? Let me show you an even geekier way to do it.

In Python, when you instantiate a class, the interpreter calls ‘__new__‘ method – a class method which returns an instance of the class – and then ‘__init__‘ method – constructor of the class – is called which initializes the object. So, you can hack into ‘__new__‘ and return the single instance whenever it is being called.

class Singleton(object):
	_instance = None
	def __new__(cls, *args, **kwargs):
	# cls is the Class and the rest are constructor arguments
		if cls._instance is None:
			# create an instance and store it
			cls._instance = Object.__new__(cls, *args, **kwargs)
		return cls._instance
class Resource(Singleton):
	def __init__(self, klass):
		self.name = None

Aweomse! Isn’t it? There are other ways that deal with ‘__metaclass__‘ etc. but let’s save them for another day. Let’s use it now:

# get resource r1
r1 = Resource();
# get resource r2  (since Resource is singleton, r1 == r2)
r2 = Resource();
# to verify, let's set 'name' onto r1
r1.name = "Animesh Kumar"
print r1.name
# and the same 'name' appears in r2 as well!
print r2.name

Let’s now see how do we do this in Javascript. For the most simple form, just define an Object Literal, and you are done.

var resource = {
	getName : function() {
		return this.name;
	},
	setName: function(name){
		this.name = name;
	}
}

Easy. You have an object which you can now share across your application modules and it just works. For more complex scenarios, like private variables and all, you might have to resort to something like this:

// self-executable wrapper function
var Resource = (function(){
	// Resouce class which is to made 'singleton'
	function _Resource() {
    	var name; // private variable
    	this.getName = function() {	// getter
    		return this.name;
    	};
		this.setName= function(name){ // setter
			this.name = name;
		};
		// do more stuffs
    }
    // instance holder
    var instance = new _Resource();</p>
    // return an object with 'getInstance' method
    return = {
        getInstance: function(){
            return instance;
        }
   };
})();

_Resource (line-04) is your function of interest, and you want to make it singleton. So, you create another function ‘Resource‘ which wraps over _Resource and returns an object with method ‘getInstance‘ which would return the same instance of _Resource every time it will be called.

Let’s try to use it now:

// get resource r1
r1 = Resource.getInstance();
// get resource r2  (since Resource is singleton, r1 == r2)
r2 = Resource.getInstance();
// to verify, let's set 'name' onto r1
r1.setName("Animesh Kumar");
console.log(r1.getName());
// and the same 'name' appears in r2 as well!
console.log(r2.getName());

So it was easy. No? Great.

Now, Java. I know every one of you would already know it. I would write about it anyway, just for the sake of completeness. In Java, you create a private static instance of the class, and use that instance wherever necessary.

public class Resource {
	// static instance (Note: Resource instantiation is done here, not in getInstance)
	private static Resource instance = new Resource();
	// property
	private String name;
	// private constructor to disable 'new'
	private Resource() {
	}
	// public staic method to get an instance of this class
	public static Resource getInstance() {
		return instance;
	}
	// getter
	public String getName() {
		return name;
	}
	// setter
	public void setName(String name) {
		this.name = name;
	}
}

Now, let’s use it.

	public static void main(String[] args) {
		// get resource r1
		Resource r1 = Resource.getInstance();
		// get resource r2  (since Resource is singleton, r1 == r2)
		Resource r2 = Resource.getInstance();
		// to verify, let's set 'name' onto r1
		r1.setName("Animesh Kumar");
		System.out.println(r1.getName());
		// and the same 'name' appears in r2 as well!
		System.out.println(r2.getName());
	}

Loud and clear. And this also stops you from instantiating ‘Resource‘ with ‘new‘ operator. Try this:

	Resource r1 = new Resource();  // java.lang.Error: Unresolved compilation problem:

Your code will not compile. I know you know why. I will write anyways: because the constructor is private! So, there is no way to get an instance of Resource class but through ‘getInstance’ method which ensures single instance of the class. Also, If you noticed: I have instantiated ‘instance’ during declaration itself, not in ‘getInstance’ method. This way, the object gets created at the time of class loading, and you save yourself from a lot of issues that creeps in because of Java Just in Time.

Advertisements

Written by Animesh

May 27, 2011 at 3:59 pm

IBM has no idea what Node.js is

with one comment

[tweetmeme source=”anismiles” only_single=false http://www.URL.com%5D

People, don’t read this article on IBM’s developer works Just what is Node.js?. And you have read it already, don’t believe it. IBM has no idea what Node is, really.

Read my rebuttal http://wkp.me/wkk6g

For more gory details, read Marak Squires’ blog here.

IBM must pull the article or ask the author to rewrite it. The article is providing a dis-service to any new developers who might stumble along it as their first introduction to node.js.

Written by Animesh

May 13, 2011 at 12:34 pm

Node and Its Many Incarnations (Node Version Management)

leave a comment »

[tweetmeme source=”anismiles” only_single=false http://www.URL.com%5D

Node.js is under active development. And every other day, a new build is released. It’s awesome to see how fast Node is growing and how vibrant the community is… but on the down side, it’s becoming increasingly difficult to keep track of its many versions, and API changes.

Very often, while developing an app, you find yourself married into a particular Node version, because a newer one might have some API changes (mind you, Node is witnessing heavy transformations, especially at the API level) which might break you app… and then, you would be forced to revert back to the older version. That means, uninstall the current node and re-install the older one. Ouch! So much work for a mere upgrade.

Well, there is a nicer way to do it. Check out this project by Tim Caswell: Node Version Manager. It does exactly what it says. It manages various Node versions on your machine, development, stage, production whatever. How?

It creates a virtual Node environment for each version you want to keep. Let’s say, you want to stay with the last stable release v0.2.6 (from the time you started your app) but also want to experiment with v0.4.7 to keep an eye on new additions.  NVM will install two separate Node(s) for you, and each will run in its own sandbox like environment, that is, you will have to install all your third party Modules/Libraries separately for each Node installation. That might seem to be a lot of work, but trust me, it’s the safest way to avoid conflicts. Okay. Let’s get to work.

Installation

Note: I am assuming that you have basic knowhow of GIT (the most awesome source control management system).

  1. Clone NVM repository to your local machine:
    $ git clone git://github.com/creationix/nvm.git ~/.nvm

    Above command would close the NVM repository to a folder ‘.nvm’ in your home directory. (I am using Ubuntu 10.0.4)

  2. Switch to folder ‘.nvm’ and make file ‘nvm.sh’ executable:
    $ chmod 755 ~/.nvm/nvm.sh
  3. ‘nvm.sh’ is just a shell script, so in order to run it, you must source it to every terminal you open. To do this automatically, simply edit either ‘.bashrc’ or ‘.profile’ file to have this line in the very end:
    . ~/.nvm/nvm.sh
  4.  That’s it. Open a new terminal and run,
    $ nvm
  5. You will see a set of useful commands you can use. 🙂 Easy huh?

Getting dirty

Before you get any further, just make sure that you have ‘wget’ installed in your machine. I know, I know… you might already have it. I just want you to make sure.

Check which versions of Node are available.

$ nvm sync // update the local machine with available versions from server
$ nvm ls   // displays all available and installed versions

Now install Node v0.4.7.

$ nvm install v0.4.7 // will install Node v.0.4.7

Note: You might get this error, “Could not autodetect OpenSSL support. Make sure OpenSSL development packages are installed. Use configure –without-ssl to disable this message” which says, that you need to install SSl library:

$ sudo apt-get install libssl-dev

NVM creates a folder ‘src’ either in your home directory or in ‘.nvm’ directory where it downloads the bundled release, extracts and installs it. NVM also installs NPM (node package manager) for each installation of Node.

Select a particular version

$ nvm use v0.4.7 // start using Node-v0.4.7

That’s it. You have set up a system which will enable you to quickly and cleanly switch between various Node versions. You can test your app’s compatibility with any of them, and if need be, easily switch to the one your app was most comfortable with.

Now, since you have set up a congenial Node development machine, in the next blog, I will talk about how to go live with your Node app.

Note: for CentOs-5.x, please make sure that you have following packages installed:

$sudo yum install gcc-c++ screen git-core openssl openssl-devel

Written by Animesh

May 3, 2011 at 11:17 am