开发者

Static (Shared in VB.NET) or Normal Methods

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?


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜