I have often pondered this one… its probably an idiot question but here goes.
Say I have this class:
public class SomeClass
{
public int AProperty { get; set; }
public void SomeMethod()
{
DoStuff(AProperty);
}
}
Is there any advantage to doing this:
public class SomeClass
{
public int AProperty { get; set; }
public static void SomeMethod(int arg)
{
DoStuff(arg);
}
}
The only advantage that is obvious is that I can now access SomeMethod directly.
So is it good practice to make these kind of methods static where a little refactoring will allow or is it a waste of my time?
EDIT: I forgot to mention (and ShellShock’s comment reminded me) that the reason I ask is that I use ReSharper and it always makes suggestions that ‘Method X can be made static’ and so on…
Staticisn’t evil.Staticis evil if used incorrectly, like many parts of our programming toolkit.Staticcan be very advantageous. As the accepted answer here points out,staticcan have a potential speed improvement.As a general rule if the method isn’t using any fields of the class then its a good time to evaluate its function, however ultimately utility methods that can be called without instantiating an object can often be useful. For instance the
DirectoryInformationandFileInformationclasses contain useful static methods.Edit
Feel obligated to point out that it does make mocking a lot harder but it is still definitely testable.
It just means you need to think harder about where
staticmethods go, so that you can always test them without needing to rely on a mock/stub. (ie: don’t put them on your DTO that requires a persistent connection to the database).