Sunday, October 01, 2006

Inheritance

I was thinking about inheritance today and how much more I enjoy programming in ObjC where inheritance is used quite little compared to C++ where inheritance seems to be used quite often. Don't get me wrong, inheritance certainly has it's place in programming and I think it's a wonderful, wonderful thing. However, it seems to me that in C++ inheritance is used and only serves to make the programmer's job more tedious. In a lot of asynchronous programming, you have listener objects which get notified when a certain event happens. In order for the notifier to know how to notify an object, often a class is declared which one must inherit from and implement it's notification methods. As it turns out, there is a struggle between making the listener object know about many other objects (thus, decreasing encapsulation) and having the listener forward the notification to another object (perhaps a controller in a MVC app) that can do the appropriate thing with it. Since multiple inheritance in many workplaces is defined as EVIL (which it is), this can be a time consuming problem. The beauty of ObjC and the Cocoa framework is that more often than not you can set ANY object to be the listener of a notification. The notifying object can either require a protocol or check at run time whether the listener implements the method. This allows for the notifier to know about as little as possible and we can provide better encapsulation without "wasting" a simple forwarding message.