Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When inheriting from a class hurts you later?

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#.

like image 791
A-K Avatar asked Sep 05 '10 15:09

A-K


1 Answers

What you are describing is one of the pitfalls of inheritance.

Another pitfall is a deep inheritance hierarchy. Stackoverflow thread on composition over inheritance.

like image 65
Chuck Conway Avatar answered Oct 06 '22 23:10

Chuck Conway