问题
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