Jacksonkr
Jacksonkr

Reputation: 32247

Using composition instead of inheritance

I come from a ECMAScript background (seems to be very C/C++). Thus, I learned classic C++ style inheritance involving classes, objects, and cool stuff like polymorphism.

I like Android and iOS development lately. Java appears to be C-based, so I'm fine using the majority of my C-based rules there, but iOS is different enough that I'm leery with my approaches -- especially with something like object inheritance.

I ask because there seem to be some strong opinions toward composition. From what I've seen with composition so far, I'm not the biggest fan unless the project provides a good reason to work with it.

You pro Obj-C/iOS devs out there, would you recommend composition over classic inheritance? Or is it a situational thing?

Upvotes: 2

Views: 3831

Answers (3)

Jeff Wolski
Jeff Wolski

Reputation: 6382

To me, this is more a question of what classes you're using. If you're using Apple's core foundation or UI libraries, I would recommend that you avoid subclassing. Many of these classes are not concrete classes but rather are class clusters. In these classes, the os may decide at runtime which class to actually use.

In general, I prefer composition unless I have a very compelling reason to subclass. Even when I have a compelling reason to subclass, I often choose instead to create a category of methods for the original class.

Upvotes: 0

hamstergene
hamstergene

Reputation: 24439

If a new class generally follows Liskov Substitution Principle towards the class that it's derived from, use inheritance, otherwise, prefer composition/aggregation. It is not one against another, both are widely used.

Upvotes: 0

Cthutu
Cthutu

Reputation: 8917

The object model of Objective-C is quite different to C/C++/Java. It is message-based and so more emphasis is placed on objects responding to messages rather than calling methods as in C/C++/Java.

The approach to the Cocoa libraries favours a flatter object inheritance hierarchy and relies on the delegate pattern for customisation and to keep those object hierarchies flat. Why do this? A lot of libraries, especially GUI, suffer from complications due to hierarchy bloat to the point that it is not clear which class you'd inherit from. Most modern object systems in video games, for example (being my industry of expertise), use composition paradigms where objects are constructed by mixing behaviors as it's more flexible and easier to maintain in practice.

I wouldn't say Cocoa libraries use the composition model as such, but rather uses the interaction between classes clearly partitioned in one of the Model-View-Controller areas and uses delegation for customisation. Keeping customisation separate from the core functionality keeps complexity down and hierarchies flatter.

Upvotes: 5

Related Questions