Avoid inheritance for implementation

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m (Reverted edits by Ebybymic (Talk); changed back to last version by JaninaVoigt)
 
(4 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
The core idea here is not to create a subclass merely to access the functionality of the superclass. An example:
 
The core idea here is not to create a subclass merely to access the functionality of the superclass. An example:
  
class Grapher extends DataList
+
class Grapher extends DataList
  
 
Now the Graphing class can use all the functionality of the DataList class. But intuitively, the declaration looks wrong, mainly because a Grapher isn't a type of DataList. A graph should have '''have''' a DataList, but it isn't strictly a list of data itself.
 
Now the Graphing class can use all the functionality of the DataList class. But intuitively, the declaration looks wrong, mainly because a Grapher isn't a type of DataList. A graph should have '''have''' a DataList, but it isn't strictly a list of data itself.
Line 9: Line 9:
 
Instead, the Grapher should contain a DataList object internally. This avoids the above issues, as well as being more semantically correct (a Graph '''has''' a DataList)
 
Instead, the Grapher should contain a DataList object internally. This avoids the above issues, as well as being more semantically correct (a Graph '''has''' a DataList)
 
== See Also==
 
== See Also==
[[Favor composition over inheritance]]
+
*[[Favor composition over inheritance]]
 +
*[[Don't burn your base class]]
 +
*[[BaseBean]]

Latest revision as of 03:05, 25 November 2010

The core idea here is not to create a subclass merely to access the functionality of the superclass. An example:

class Grapher extends DataList

Now the Graphing class can use all the functionality of the DataList class. But intuitively, the declaration looks wrong, mainly because a Grapher isn't a type of DataList. A graph should have have a DataList, but it isn't strictly a list of data itself.

This will cause problems since Grapher exposes its internal data list to outside classes (bad for encapsulation), we can't extend the class easily if we want a graph that draws two lists of data, rather than a single one, and also, we are creating unnecessary class hierarchy.

Instead, the Grapher should contain a DataList object internally. This avoids the above issues, as well as being more semantically correct (a Graph has a DataList)

See Also

Personal tools