Wednesday, February 23, 2011

static methods VS singleton

Well this is an old topic but i've never seriously thought about it. We can grab a lot articles from internet, but here is what i agree most:

1. singleton is an instance, instance is an object. so, you can pass it as a parameter. If you were using static classes, the other function would have to use the class statically too and if you ever needed to change the behavior, you would need to rewrite parts of that function too instead of just having the first one pass a different class as the parameter.

2. You can also give a singleton some parameters. When working with static classes, you may need to pass a lot of parameters to the methods of the class because you aren't "constructing" it

3. singleton can become multiton(read db connection, write db connection)

4. If you use the reference in your class and decide that you won't need a singleton anymore, but a normal class, you will just need to change the behavior of the class itself and perhaps replace the line which gets an instance of it to constructing a new one or such. If you were using a static class, you would have to rewrite a lot of the code to use the new reference to the class instead of the static class name. A singleton class should also work almost out of the box as a normal class too. If you had a static class and wanted to convert it to a normal one, you would have to rewrite many parts of it.

6. You can't extend static classes, but singletons you can. Except it doesn't work very well in PHP due to some issues with static method inheritance, but it's not the only language in the world and it can be done but slightly hackily

7. Last and least:D dude, you can find many singleton in Zend Framework. Could you find any static class there?

So to the end, where is the place for static methods? Well, they definitely have their places too:
For example for library code they can be nice, such as the static System.Math class in C#

No comments: