Re: Composition vs. Inheritance (Was: colored point redux)
Robbert Haarman <[email protected]> Mon, 26 Feb 2007 14:35:59 +0100
| Newsgroups | gmane.comp.lang.lightweight |
|---|---|
| Message-ID | <[email protected]> |
On Sun, Feb 25, 2007 at 10:21:28PM -0500, Vadim Nasardinov wrote: > On Sunday 25 February 2007 06:45, Pascal Costanza wrote: > > On 25 Feb 2007, at 04:23, Vadim Nasardinov wrote: > > > > As Eric Gamma says, "Favor composition over inheritance": > > > > Yes, just another opinion. > > It's an opinion based on the following cold hard fact > (Message-Id: <[email protected]>): > > | There's a tight coupling between the base class and the subclass, > | because of the implicit context in which the subclass code I plug > | in will be called. Composition has a nicer property. The coupling > | is reduced by just having some smaller things you plug into > | something bigger, and the bigger object just calls the smaller > | object back. From an API point of view defining that a method can > | be overridden is a stronger commitment than defining that a method > | can be called. I am intrigued by the suggestion that composition is somehow better than inheritance, in part because I am designing a programming language, and things would be easier if I wouldn't have to provide for inheritance. However, all the arguments I have read in favor of composition over inheritance seem weak and/or wrong to me. First, the example put forward by Erich Gamma of customizing the behavior of a JPanel by adding an object that implements MouseListener. I agree that this is clearly the right way to go if the alternative is subclassing the JPanel and overriding some method that handles mouse events. In fact, using inheritance in this scenario probably wouldn't even have occured to me. Therefore, I don't see how the example argues in favor of using composition instead of inheritance. To me, it's like saying it's better to use a screw driver than a napkin for fastening a screw. Rather than looking at a scenario where inheritance (to me) is clearly not the right tool for the job, I would consider what inheritance actually is. To me, it means that behavior defined for one type of object is inherited by another type of object. For example, an employee is also a person, and thus has a name method just like a person does. Or, another example, strings and linked lists are both sequences, and thus could inherit some behavior (methods) that are common to all sequences. How would this be accomplished by composition? Regards, Bob -- A man should practice what he preaches, but a man should also preach what he practices. -- Confucius
signature.asc
(application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) iD8DBQFF4uI/fb9wcmD+WN4RAnTPAJ9Fw9lzzlqr9IM9bDHJ6g7ZyJQGUQCbBY2O jI4jGl86SKcgo3gnh15VzL0= =RCg7 -----END PGP SIGNATURE-----