tags:

views:

108

answers:

4

While developing an application in OOP, should static methods be avoided as much as possible?

A: 

In my opinion, static methods are simpler than instance methods, and therefore they should be used as much as possible.

The thing is to know when it's not possible: which is usually, i.e. whenever the method needs to read or write object/instance data members.

ChrisW
A: 

It depends - a static method is necessary in a OOP language such as Java or C# if you really just need to write a stand-alone function. In this case you might create some sort of Utility class that contains various static methods.

Justin Ethier
+1  A: 

No, they shouldn't.

Any method that does not operate on an instance of an object should be static.

There is no point in requiring an object instance if you don't need it.

SLaks
Can you explain why?
Richard Ev
@Richard: Why should they be avoided? What is there to explain?
SLaks
There's some things that don't logically make sense instantiating. For example the Java `Math` class (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html). Why should I have to do `Math m = new Math();` just to perform a square root operation? Here a static method makes sense: `Math.sqrt(27);`
Lotus Notes
+1  A: 

There are very specific cases that prescribe their use such as passing a class method to a C API that needs a function pointer or a means to create certain patterns such as Singleton. Generally you don't want to use one unless there is a good reason.

They are otherwise discouraged because their use beyond some limited cases implies you have global data present since they don't have automatic access to the 'this' pointer. That violates OO principles such as data hiding.

Amardeep