Is it a good or bad practice to have static methods without attack?

If a class method does not rely on the state of the class, it may be static. Is it good or bad practice to make such methods static, if so?

(tagged C #, but probably applies to many language versions where the methods must be members of the class.)

+5
source share
2 answers

Visual Studio Code Analysis and ReSharper offer to make these methods static, because there is a slight performance advantage:

From the documentation :

Members that do not access instance data or do not invoke instance methods can be marked as static (Shared in Visual Basic). After you mark methods as static, the compiler will send non-virtual call sites to these participants. Creating non-virtual call sites will prevent run-time checking for each call, which ensures that the current object pointer is not zero. This can provide a tangible performance boost for performance-sensitive code. In some cases, the inability to access the current instance of the object presents a validity problem.

For non-performance-sensitive code, this is a matter of taste. I personally submit to ReSharper's suggestions if I have no good reason not to.

+4
source

Is it good or bad practice to make such methods static, if this is the case?

Honestly, one cannot say 100% is good or bad practice. Many people follow a general rule: if it can be made static, do it. This shows that there is no state requirement and technically (at least in C #), it is a little faster.

Thus, it all depends on the composition of the code around the methods and how the application will develop.

+1
source

Source: https://habr.com/ru/post/1262363/


All Articles