开发者

In a composite object, are almost identical functions in the parent and child objects common?

Say I have a Timer object which has a TimerDisplay object as one of its properties. If I have a update(hours, minutes, sec开发者_运维知识库onds) method in the TimerDisplay object, which of the following (if any) are a good practice:

  • have an updateDisplay(hours, minutes, seconds) method in the Timer, which calls the corresponding update method in the TimerDisplay
  • allow a direct call to timer.timerDisplay.update(hours, minutes, seconds)

I'm just starting OO, by the way. The first seems to be more OO, but ends up with two almost identical methods. The second seems easier, but doesn't it go again encapsulation?

Thanks in advance


The direct access to timer.timerDisplay sounds like a bad idea (as public attributes are most of the time). If you don't want to have the timer class bother with comunicating with the timerDisplay, then why have timerDisplay be a property of a timer? Just have the same guy that is updating the timer own the display himself then.

On the other hand, if you want the Timer class to manage updating the display, then limiting it to managing only one display doesn't sound that good. Why not have it keep a list of displays to notify instead? If you choose to have the Timer do the communication like this, then hiding it behind the Timer.update method sounds best at least.

As an aside, if you don't like the TimerDisplay having methods too similar to the timer, perhaps you can use a simpler method like

TimerDisplay.updateFrom(timer)

using timer.getHours(), etc instead of passing tons of parameters everytime.


Lastly, depending on how complicated your problem is, you might get away with just fusing both classes into a single class. It is less modular, but simplicity also has its virtue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜