方法调用同一个类中的其他方法
在类设计中,如果一个方法调用同一个类中的另一个方法(例如,同一个类中3个方法调用1个方法),这是一个坏习惯吗?
谢谢
In class design, is it a bad habit if one method calls another method in the same class (For example, 3 methods call 1 method in the same class).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
完全不是,如果你正确设计了你的类,这是可以预料到的。您应该有一个小的公共接口,如果实现很复杂,您可能最终会在同一个类中调用许多私有方法。
事实上,不这样做可能是一种反模式。如果您不断调用另一个类的方法,则称为“功能嫉妒”,您可能应该组合类。如果您将所有实现都放入一个庞大的函数中,那么这是无法维护的,并且可能包含大量重复代码。
将事物分解为其他可重用的方法是一件好事。您的 3 个方法调用同一个方法的情况是完美的代码重用。如果该函数的代码在每个调用函数中重复,那将是非常糟糕的。
Not at all, it's expected if you've designed your classes properly. You should have a small public interface, and if the implementation is complex, you'll probably end up calling many private methods in the same class.
In fact, not doing this can be an anti-pattern. If you're constantly calling methods of another class, it's called Feature Envy and you should probably combine classes. If you're putting all the implementation into one gargantuan function, that's just unmaintainable, and probably contains a lot of code duplication.
Breaking things out into other reusable methods is a good thing. Your case of 3 methods calling the same one is perfect code reuse. It would be very bad if the code of that one function was duplicated in each of the calling functions.
不。事实上,这样做是一种很好的做法。或者您是否认为执行调用的三个方法都应该复制被调用的代码?
No. In fact it is good practice to do this. Or do you think that your three methods that do the calling should each duplicate the called code?
方法只是函数,函数是对代码重用和设计改进有用的抽象。如果一个类的三个方法在运行时需要做同样的事情,他们应该复制粘贴代码还是调用一个单独的方法?
将代码的一些有意义的部分分离到一个由其他方法调用的方法中只是代码重用的另一个示例,除非您真的做得太过分,否则这很好。
Methods are just functions and functions are abstractions useful for code reuse and design improvement. If three methods of one class need to do the same thing while running should they copy-paste the code for that or call a separate method?
Having some meaningful part of code separated into a method being called by other methods is just another example of code reuse which is good unless you really overdo it.
不会。看来您已经找到了维护DRY 原则的有效用途。
No. It appears that you have found a valid use to uphold DRY principles.
一点也不。事实上恰恰相反。方法是用来完成特定任务的,您应该准确地使用它们。
Not at all. Infact quite the opposite. Methods are there to accomplish specific tasks, and you should use them for precisely that.
是的,如果这些方法是可重写的,即如果类和/或方法不是最终的。原因是尝试覆盖行为或提供服务层的子类无法可靠地做到这一点,因为该层可以多次进入。
示例(Scala 伪代码),我们假设
HashSet.addAll
调用自己的HashSet.add
:当使用
addAll
时,我们现在最终会得到双重结果:计数。Yes, if those methods are overridable, i.e. if the class and/or methods are not final. The reason being that subclasses that attempt to override behavior or to provide a layer of service cannot do so reliably because the layer can be entered multiple times.
Example (Scala pseudo code) where we assume that
HashSet.addAll
calls its ownHashSet.add
:When using
addAll
we now end up double-counting.