Search code examples
.netoptimizationclrdevexpresscoderush

CodeRush suggests making a method static if it has parameters, agree or disagree?


I use Developer Express's CodeRush product which has a feature called Code Issues which makes suggestions to optimize your code. I've noticed that if you have a method that has parameters it will always suggest making this method static. In the spirit of trying to write the best code and optimized which I assume is what DevExpress is trying to help us do, I've heard mixed opinions on whether making the method static is in fact wise.

What is your opinion on when a method should be static? Is there any benefit to doing this? Impact? I don't see anything wrong with it as it is requiring parameters to run the method so it is not something that would be an issue across multiple users/uses.

Good or Bad?

Thanks.


Solution

  • As others have indicated, the presence of parameters is not a consideration. The hint is present when the method does not access any instance members.

    When is this useful?

    When a candidate method requires no state to perform it's function, it should not be required that the caller of this function possess or create an instance of the parent class.

    By removing this requirement, the calling code will surface errors (or in some languages warnings) indicating that the method in question "cannot be accessed with an instance reference" requiring a Type Reference instead.

    When the calling statement is rewritten to use a Type reference, it may be discovered that the original instances of the type is not required and code may be refactored further to eliminate he creation of same.

    The elimination of this instance type will save cpu and memory.

    The calling method (or it's own callers) will likely be easier to read since instantiation code is not needed for the method in question.

    Additionally if instantiation code is missing, this will add to the readability of one or more methods.

    For example the System.Math class is static and therefore filled with static functions. Calling code for these functions would be less readable if it had to instanciate an instance of the math class prior to execution.