1

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.

mrflash818
  • 930
  • 13
  • 24
corsel
  • 315
  • 2
  • 12

1 Answers1

4

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Well... Maybe I'll just refactor to put the functionality inside the classes. Or just ignore good OOP practices and go a bit functional. – corsel May 21 '18 at 15:48
  • 1
    @corsel It’s not good functional practice either. – Konrad Rudolph May 21 '18 at 15:52
  • Why's that? Wouldn't it be more or less small classes as data containers and stateless functions modifying the data? A characterless hybrid then I guess :) – corsel May 21 '18 at 16:27
  • OK, I just took a look at the functional programming concepts and yeah, it doesn't fit in there either. – corsel May 21 '18 at 16:37