Method can be made static, but should it?

2018-12-31 20:00发布

Resharper likes to point out multiple functions per asp.net page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?

13条回答
浅入江南
2楼-- · 2018-12-31 20:27

Marking a method as static within a class makes it obvious that it doesn't use any instance members, which can be helpful to know when skimming through the code.

You don't necessarily have to move it to another class unless it's meant to be shared by another class that's just as closely associated, concept-wise.

查看更多
泛滥B
3楼-- · 2018-12-31 20:32

I'm sure this isn't happening in your case, but one "bad smell" I've seen in some code I've had to suffer through maintaining used a heck of a lot of static methods.

Unfortunately, they were static methods that assumed a particular application state. (why sure, we'll only have one user per application! Why not have the User class keep track of that in static variables?) They were glorified ways of accessing global variables. They also had static constructors (!), which are almost always a bad idea. (I know there are a couple of reasonable exceptions).

However, static methods are quite useful when they factor out domain-logic that doesn't actually depend on the state of an instance of the object. They can make your code a lot more readable.

Just be sure you're putting them in the right place. Are the static methods intrusively manipulating the internal state of other objects? Can a good case be made that their behavior belongs to one of those classes instead? If you're not separating concerns properly, you may be in for headaches later.

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 20:33

You should do what is most readable and intuitive in a given scenario.

The performance argument is not a good one except in the most extreme situations as the only thing that is actually happening is that one extra parameter (this) is getting pushed onto the stack for instance methods.

查看更多
只若初见
5楼-- · 2018-12-31 20:34

If the functions are shared across many pages, you could also put them in a base page class, and then have all asp.net pages using that functionality inherit from it (and the functions could still be static as well).

查看更多
心情的温度
6楼-- · 2018-12-31 20:34

Making a method static means you can call the method from outside the class without first creating an instance of that class. This is helpful when working with third-party vendor objects or add-ons. Imagine if you had to first create a Console object "con" before calling con.Writeline();

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 20:35

It helps to control namespace pollution.

查看更多
登录 后发表回答