开发者

Is it better to use static functions if no class members are needed?

I have a me开发者_StackOverflowmber function that does not depend on any member variables of the class. (in my case the class is an ASP.Net Page)

The function is protected, I dont need it outside of this class. Its only purpose is to build an URL from an given object.

Should I make all my functions static if they dont depend on the class, even if they are not used outside of this class? Is there any reason like performance or maintainability to do so?


Probably, but I'd take it a step further.

In these situations you really want to ask yourself if the method still belongs with the type at all. If this method has no dependence on the type's data, why is it part of that type? Is there a better or more appropriate type? Do you have several of these, perhaps scattered among a few different types, that could be logically grouped together?


It is good practive to make functions that don't interact with member data static. It just helps describe how the function interacts with its environment. There should be no performance issues though.


Yes; they should be static.


I can't say I know enough about the performance, but I've heard that it's a good idea to make it static if it doesn't depend on class members. Usually it gives you the benefit of not having to waste an allocation in case you just need that method, but since it's just inside the class for you, you're probably already working with an instance of your object. I would make it static, but in your case I don't know if there's much difference (from a coding perspective).


If you make the method static you will not need to instantiate a class to use it. This will be quicker. Also, if its static I find it makes the code a little shorter.

I dont think there are any performance issues with static, if anything its quicker. Just think of all the extension methods that have appeared in newer versions of .net. they are all static!


It depends actually. Whether your method uses any instance data or not is an implementation detail of this method. If it's private than you can make it static if you want. However, if it can be visible outside of your class (e.g. it's protected method) you should think about interface first and make it static only if it would never make sense for this method to access object data.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜