仅具有公共静态方法的帮助程序类 [英] Helper classes with only public static methods

查看: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.

这被认为是不良的OOP做法吗?是否有一种确定的更好的方法可以实现这一目标,或者为类似的案例提供类似模式的名称,以便我可以在互联网上进行进一步的研究?

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?

谢谢.

推荐答案

这被认为是不良的OOP做法吗?

Is this considered a bad OOP practice?

绝对.实际上,它只是 not OOP 1 .这样做本身很好,但是使用类是不必要的麻烦.

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

是-使用命名空间:"helper"函数几乎绝对在类中没有位置.

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.

如果您有很多公共函数正在访问类型的私有成员,那么这很好地暗示了您的界面太宽泛,或者您的类正在进行的事情太多(请记住"S" SOLID:每个角色一个责任)班级).现在该重构了.您的辅助函数现在可能应该了解其他类.相反,您的其他类应调用这些帮助程序,并将数据成员作为参数传递.

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 不是的意思是此代码使用了一个类".相反,这是一种编写代码的方法,该代码将行为按逻辑分组,以实现封装,抽象和(运行时)多态性.类是实现此目标的工具,但它们本身并不是目标.要做您打算做的事情不会对数据及其行为进行分组(相反:如果有的话,它将数据分开),并且也无助于抽象,封装或多态.

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.

这篇关于仅具有公共静态方法的帮助程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆