Anyway, apart from bringing up some great topics about programming principles in general, 22 minutes into the podcast they bring up inheritance and remembering my education in object oriented programming I've always learned that inheritance is a "is-a" relationship. When deciding if class A should derive from class B you can always ask yourself if "A is a B".
Example: I have two base classes called Vehicle and Person. Now I am to create a class called Car and another one called Employee. A Car is a Vehicle and therefor Car should derive from Vehicle. An Employee is not a Vehicle but is a Person and will derive from Person. Pretty simple.But according to Uncle Bob it's just not that simple. He brings up the old example with the Rectangle and Square. A Square is a Rectangle and according to the above mentioned rule a Square should derive from the Rectangle. But a Rectangle has a height and a width, and the Square only needs one variable. So the Square will inherit the wrong set of variables. Not a big problem maby, we just work around the problem so when you set the height of a Square the width is set too. But then the creator of the base class Rectangle wants to build a function that depends on the height and not the width. He knows that when you set the height, the width is not affected in a Rectangle. So he builds his function. But then you get problems with the Square, since this sets both the height and with at the same time. A Square is a Rectangle sounds right, but something is wrong.
In geometry the two objects are related, but not in code. They have completely separate behavior and therefor are not related at all. So inheritance really has nothing to do with is-a relationships it's just "a declaration of methods and variables in a sub scope" according to Uncle Bob.
I'll have to think about all of this for a while but for the time being I'll have to watch myself when dealing with inheritance, especially if I try to follow the SOLID principles. But somewhere I can't help to wonder if I would have grasped the basics of object oriented programming without the is-a. In most cases it really works.
Go ahead and check out the podcast and send some comments my way on this subject.
Post a Comment