Can you provide scenarios when we inherit from a class, it works for a while, but then something else changes and introduces a bug?
I came up with the following situation:
- to implement Rectangle-with-hole, we inherit from class Rectangle. In the constructor, we check that the hole is inside the rectangle
- Later someone adds a new method Resize to class Rectangle. They don’t check if the hole is still inside.
- After Resize, we can have Rectangle-with-holes with holes not inside rectangles, which is a bug.
What are the other problems I should be careful if I choose to use object inheritance in C#.
There are many ways a change to a base class can affect derived class behaviour. What if the author suddenly decided to make the class
sealedfor example?Like any interface it needs to be stable if consumers are to not require modification.
The primary “rule” with inheritance is the Liskov Substition Principle. This states that the derived class should be substitutable for the base class or other classes derived from it.
This case breaks this rule on the face of it, as a rectangle with a hole is not a rectangle.
Usually it’s best to use interfaces to divide behaviour into sensible implementable chunks. Such interfaces are generally named with adjectives rather than nouns. For example, it makes sense for both a rectangle and a rectangle with a hole to be rendered, so an interface might be
IRenderable. If it’s resizable you might have aIResizable, etc. These could be aggregated into anIShape, but you want to be careful that your definition of Shape defines just the behaviours in your problem domain.Directly deriving from another class can be dangerous as you’re then bound by the behaviour of that class. If you genuinely need to do that it can be best to extract the implementation you need into a common base class (e.g.
Rectangle : RectangleImplementation, IShape).