Helper classes with only public static methods [closed]

折月煮酒 提交于 2021-01-28 06:02:37

问题


I wish to create a helper class with public static methods only. I declare a class instead of namespace, because I will befriend this class with others so that it can operate on their private members as well.

Is this considered a bad OOP practice? Is there an established better way to achieve this goal, or a pattern-like name given to cases like this, that I can do further research on the internet?

Thanks.


回答1:


Is this considered a bad OOP practice?

Absolutely. In fact, it’s simply not OOP1. That in itself is fine, but the use of a class is unnecessary cruft.

Is there an established better way to achieve this goal

Yes — use namespaces: “helper” functions almost categorically have no place inside classes.

I will befriend this class with others so that it can operate on their private members as well.

If you have lots of public functions accessing private members of a type, that’s a good hint that your interface is too broad, or that your class has too many things going on (remember the “S” SOLID: one single responsibility per class). It’s time to refactor. Your helper functions should probably now know about your other classes. Instead, your other classes should invoke these helpers and pass data members as parameters.


1 OOP does not mean “this code uses a class”. Rather, it’s a way of writing code that logically groups data with behaviour in order to achieve encapsulation, abstraction and (runtime) polymorphism. Classes are a tool to achieve this goal, but they are not a goal in their own right. Doing what you intend to do does not group data and its behaviour (on the contrary: if anything, it splits it apart) and it does not aid abstraction, encapsulation or polymorphism.



来源:https://stackoverflow.com/questions/50452161/helper-classes-with-only-public-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!