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