开发者

Methods calling other methods in the same class

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).

开发者_如何学CThanks


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.


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.


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 own HashSet.add:

class MemCountingSet[T] extends HashSet[T] {
  private def sizeOf(t: T) = ...

  private var memCount = 0

  def add(t: T) = {
    memCount += sizeOf(t)
    super.add(t)
  }
  def addAll(coll: Collection[T]) = {
    memCount += coll.foreach(sizeOf)
    super.addAll(coll)
  }
}

When using addAll we now end up double-counting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜