Is it good or bad practice to make stateless methods static?
Asked Answered
I

2

8

If a class method doesn't rely on the class' state then it can be static. Is it good or bad practice to make such methods static where this is the case?

(Tagged as C# but probably applies to many OO languages where methods must be class members.)

Inelastic answered 5/1, 2017 at 14:54 Comment(1)
Paging @JonSkeet, definitely seems like his kind of question.Harewood
S
5

Visual Studio Code Analysis and ReSharper suggest to make those methods static, because there is a tiny performance advantage:

From documentation:

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

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

Stogner answered 5/1, 2017 at 14:57 Comment(2)
I wasn't aware MSDN covered such details, that's really useful to knowInelastic
@Mr.Boy it's not really the MSDN, but VS Code Analysis, the MSDN only covers the explanation why CA suggests it.Mullis
K
1

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

Honestly, there is no way to say if 100% this is good or bad practice. A number of people follow the general rule that if it can be made static then do so. It shows that there isn't a requirement on state, and technically (at least in C#) it is a little faster.

That being said, it all depends on the composition of the code around the methods, and how the application is going to evolve.

Kenyettakenyon answered 5/1, 2017 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.