Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Inheritance is better when some condition is checking something intrinsic to your object that you check constantly (like a state or type). In this example, it's an operator for a mathematical expression tree. An operator, like addition, has an expression before and after the plus sign (<a href="http://en.wikipedia.org/wiki/Infix_notation" rel="nofollow noreferrer">infix notation</a>) so I call them left and right because it is represented as a tree. There are also unary operators like a hyphen that negates a value, but it only has one child expression.</p> <p>Using inheritance means the type (simplified to just unary vs. binary) is factored into the inheritance:</p> <pre><code>class Operator { abstract string ToString(); } class UnaryOperator : Operator { Expression Expression { get; } override string ToString() {...} } class BinaryOperator : Operator { Expression LeftExpression { get; } Expression RightExpression { get; } } class AdditionOperator : BinaryOperator { override string ToString() { return this.LeftExpression.ToString() + "+" + this.RightExpression.ToString(); } } </code></pre> <p>As opposed to:</p> <pre><code>class Operator { Expression LeftExpression { get; } Expression RightExpression { get; } OperatorType Type { get; } string ToString() { switch(this.Type) { case OperatorType.Addition: return this.LeftExpression.ToString() + "+" + this.RightExpression.ToString(); case OperatorType.Negation: return "-" + this.LeftExpression.ToString(); case ...: } } } enum OperatorType { // Unary operators Negation, // Binary operators Addition, Subtraction, Multiplication } </code></pre> <p>Here your Unary operator doesn't have a Left and a Right expression, just an expression. This means you have to introduce convention that Left is used and Right is null. ToString would have to check OperatorType; so would any other method that needs to act on what operator it is.</p> <p>The latter approach is most often seen in XML DOM implementations where XmlNode is pretty much everything any XML node could contain...ever. It makes for some very confusing situations:</p> <ul> <li>How can an attribute or text node have ChildNodes?</li> <li>How can a document have ChildNodes when it can only have one? (It need not be a collection)</li> <li>How can a document have a ParentNode?</li> <li>How can a document have a Value?</li> <li>Etc.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload