Should all methods be static if their class has no member variables

前端 未结 20 2359
悲哀的现实
悲哀的现实 2020-12-02 14:18

I\'ve just had an argument with someone I work with and it\'s really bugging me. If you have a class which just has methods like calculateRisk or/and calc

20条回答
  •  感情败类
    2020-12-02 15:11

    Statics smell

    In most cases, a static method is an example of behavior divorced from data. It indicates something is not encapsulated. e.g. if you see validate methods for phone number, email etc in util classes, ask why they aren't these fields don't have their own classes. Even library classes can be extended to accommodate custom behavior. Finally in special cases like java.lang.String (which is final) you could use a custom myproject.String (with additional behavior) that delegates to java.lang.String

    Objects are the way to access behavior in OO languages. It is not useful to worry about the cost of object instantiation and use statics instead. For most business software, this is a 'penny wise pound foolish' approach to performance.

    Sometimes, you use functors (methods that don't use object state) for expressing intent. Doesn't mean they should be made static. IDE warnings that suggest "method can be made static" should not be taken seriously.

提交回复
热议问题