开发者

Is it bad programming design to delegate information from Class A to Class B to Class C instead of directly from Class A to C?

I'm planning on making an app that contains a piano keyboard. There will be a custom class that represents an individual key, and the keys will be the subviews of another custom class, the piano class. An instance of the piano class will then be instantiated into a viewcontroller.

I need a class for the keys because when a touch event occurs, I need to know which key is being pressed. When a touch event actually occurs, the key will notify the piano which key it is through delegation, and the piano will respond by relaying that same information to the viewcontroller, also through delegation.

The reason that I don't want the info to be passed from the key straight to the viewcontroller is that I'm not going to be directly instantiating instances of the key class in the vc, and it would be mor开发者_如何学Pythone readable the former way.

Is passing info from the key to the piano to the viewcontroller bad design?


It's not bad design at all. Assuming the view controller has no knowledge of the way that the piano view sets itself up (including the fact that it adds a bunch of subviews to handle its keys), this is just an example of hiding your logic as per correct object oriented design principles. All the view controller should have to know is that it can create a piano view and that the piano view will tell it which keys were pressed. In your implementation, that's all it does know.

That is, of course, assuming the piano view creates key views for itself. If you have a piano view that somebody else has to add keys to but which then expects to receive key delegate messages then I'd argue that's bad design based on the number of actors that need to know each other's implementation details.


I don't think so. In this case especially, I think it's actually good design.


I'm not sure I fully get your key - piano - viewcontroller design. But based on the subject.

It's not bad. if B is protecting A from C. It means A never needs to know about C. This is covered in a 'law' of object oriented design called the law of demeter. Not that it really is a 'law' but more of a design guideline. It promotes decoupling objects so they don't have to know anything but a few closely related objects.

http://en.wikipedia.org/wiki/Law_of_Demeter

or even, with diagrams using A B and C as per the question..

http://www.aspiringcraftsman.com/tag/law-of-demeter/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜