views:

138

answers:

3

Hi,

I Want to know which one is preferred while coding to use Static Methods or normal instances, I prefer to use static if they where few but if there was many of them I start to get some doubts

Ex

EmployeeCollection EmpLst = EmployeeManager.GetAllEmployees();

Or

EmployeeManager EmpMgr = new EmployeeManager();
EmployeeCollection EmpLst = EmpMgr.GetAllEmployees();

if the EmployeeManager Has Many methods (selects deletes updates) is it ok to make them all static.

and if it was Normal instance. wouldn't be a drawback if the object is initiated every time specially if GetAllEmployees() is heavily used.

What is the better approach to use?

+1  A: 

You might want to take a look at the factory and singleton patterns, which are creational patterns conceived for this kind of stuff. For your problem, I would suggest using a singleton, which enforces one-time creation of the object.

Abstract Factory

Singleton

(Links to dofactory.com)

Dominiek
IMHO, singletons are heavily overrrated...
Maximilian Mayerl
Care to elaborate on that?
Dominiek
Well, what'S the advantage of a singleton? Yeah, you can create a singleton on top of a derived class, but that all, sin't it? The only other difference between a singleton and a static class is that you have the overhead of accessing the Instance-property for singletons.
Maximilian Mayerl
Agreed, but it can help when the amount of instances needs to be limited. For instance when you only want 5 instances of a class around and want to balance requests between them. Nonetheless, it is also my opinion that a class with static members is equivalent in this case.
Dominiek
Static classes cannot be polymorphic. No inheritance, interface implementation or the like. A singleton approach enables you to have the best of both worlds.
AZ
+2  A: 

If you have lots of static methods, then I assume you are not following OOP principles. Static methods are helpful as factory methods or as an auxiliary methods. But I'd avoid to build application design on top of them.

Vitaliy Liptchinsky
but in ASP.NET Application the object is disposed every time the request is finished and sent. so I have to initiate the object every time I want to call the method, wouldn't be that a drawback?
Kronass
First of all you should care about design, not performance. After you've designed well, you can check if performance is acceptable and if it is not - only then you can start considering static methods or anyother approaches.
Vitaliy Liptchinsky
Thank you very much that was very useful
Kronass
A: 

In the case of your GetEmployee Method, I'd stick with static.

I normally use static if the Method doesn't need to access any instance state and instance methods if it needs to. So, I don't use instance methods if the method doesn't need instance state.

Maximilian Mayerl