Is there anything wrong with a class with all static methods?

后端 未结 16 1048
余生分开走
余生分开走 2021-01-30 16:43

I\'m doing code review and came across a class that uses all static methods. The entrance method takes several arguments and then starts calling the other static methods passin

16条回答
  •  盖世英雄少女心
    2021-01-30 17:14

    Passing all state as method parameters can be a useful design pattern. It ensures that there is no shared mutable state, and so the class is intrinsicly thread-safe. Services are commonly implemented using this pattern.

    However, passing all state via method parameters doesn't mean the methods have to be static - you can still use the same pattern with non-static methods. The advantages of making the methods static is that calling code can just use the class by referencing it by name. There's no need for injection, or lookup or any other middleman. The disadvantage is maintanability - static methods are not dynamic dispatch, and cannot be easily subclassed, nor refactored to an interface. I recommend using static methods when there is intrinsicly only one possible implementation of the class, and when there is a strong reason not to use non-static methods.

提交回复
热议问题