Method can be made static, but should it?

后端 未结 14 1250
说谎
说谎 2020-11-22 17:16

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

14条回答
  •  再見小時候
    2020-11-22 17:29

    I hope, you have already understood the difference between static and instance methods. Also, there can be a long answer and a short answer. Long answers are already provided by others.

    My short answer: Yes, you can convert them to static methods if Resharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that, unnecessarily you do not slip any instance members to that method. In that way, you can achieve an OOP principle "Minimize the accessibility of classes and members".

    When ReSharper is suggesting that an instance method can be converted to a static method, it is actually telling you, "Why the .. this method is sitting in this class as it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper.

提交回复
热议问题