Tuesday, April 13, 2010

When should a class be Static? - A realistic scenario.

After learning how the word Static plays its magic, it's important to know when can that be used in a realistic scenario. I will share an experience where I learnt a classic example of when a class should be static.

I was developing a class which was going to provide some helper methods for a functionality, say like it was a class which used to do all the data gathering part. So the methods in it were connecting with the database, constructing the query on basis of the input, getting the data, filling it into a collection (e.g: Map or TreeMap) and returning it to the calling function. The functions of this class were to be called by many other classes which were not static (or non-static..it doesn't really matter.) Let's call this class as Helper class. And other calling classes as A, B and C classes.

I first made the Helper class non-static. I always questioned myself why it should be static...there is no need! And that was correct! This class could have been non-static! When it is not static, the calling class A needs to create an instance and then call the methods of the Helper class. Like this...

Helper help = new Helper();
help.getCutomerData(param1,param2,param3) ;

There was nothing technically wrong with it... but.. as we say..this was a realistic scenario.

I began to think on these lines - does the Helper class has any instance variables? does it have any state? Or is it just a class with methods which help the calling classes? Are the methods using any instance variable? Is any output of the methods stored in the instance variables??  Answer to all these questions was No. I do not need to maintain the state of that class, it was okay if I make it static and the calling function calls directly the methods of the static Helper class. Thus this class has to be made static.

The calling class can call the non-static methods of this static Helper class by this way...

Helper.getCustomerData(param1,param2,param3);

Simple! Crisp! Logical!

1 comment:

Kiran Shigli said...

Well explained...keep posting...