When to Use and When Not to Use Inheritance

When inheritance was first introduced into some other languages, it caused problems as users went too far, creating deep and overly complex inheritance trees. Inheritance is powerful and useful, but should not be overdone. I remember working with a developer. He spent an entire day working on the design of objects and finally said, “I can't figure out where to use polymorphism.” My suggestion was that if he couldn't find where to use it, maybe he didn't need to.

There are actually three ways to build an object model:

  • Encapsulation— If you want to use functionality from an object, but not really look like the object or override its functionality, don't inherit; instead, encapsulate an instance of the object. Example: You have a calculator application, and you want to show the number display in red when it is negative. You could define a new type of control from the TextBox or Label controls that show the number in red when negative, or you could just hook onto the Change event of the text box, and perform the functionality there.

  • Interface implementation— If the derived objects don't share very much in terms of implementation, use an interface instead of a common base class. There is not much point in having a base class for which all the methods must be overridden; an interface would probably be a better way to go. Classes can also implement multiple interfaces, so a car may implement both iGasPowered and iDrivable, whereas an airplane might implement iGasPowered and iFly. A bird, on the other hand, implements iEatWorms and iFly, but does not implement iGasPowered or iDrivable.

  • Inheritance— Use inheritance if you want to utilize functionality in the base class and extend it while trying to look like the base class. If some of the methods in the base class are not appropriate for your derived class, it is probably a good indication that inheritance was not the right move. In some cases, merely encapsulating another class instance and proxying calls to it might be a cleaner solution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.222.175