Everything, Everything

2024: January February March
2023: J F M A M J J A S O N D
2022: J F M A M J J A S O N D
2021: J F M A M J J A S O N D
2020: J F M A M J J A S O N D
2019: J F M A M J J A S O N D
2018: J F M A M J J A S O N D
2017: J F M A M J J A S O N D
2016: J F M A M J J A S O N D
2015: J F M A M J J A S O N D
2014: J F M A M J J A S O N D
2013: J F M A M J J A S O N D
2012: J F M A M J J A S O N D
2011: J F M A M J J A S O N D
2010: J F M A M J J A S O N D
2009: J F M A M J J A S O N D
2008: J F M A M J J A S O N D
2007: J F M A M J J A S O N D
2006: J F M A M J J A S O N D
2005: J F M A M J J A S O N D
2004: J F M A M J J A S O N D
Inheritance
Tuesday 24th January, 2006 14:35 Comments: 0
A snippet from something I read online:

The first mistake was imagining that because the objects had some common attributes, they were related and should share an inheritance tree. Unfortunately, this is another case where software is not real life. Just because we put entities in the same box in reality, it doesn't necessarily follow that the objects representing them in a computer system share a common hierarchy.

The OO design principle that covers this is the Liskov Substitution Principle (LSP), which Bob Martin expounded in his programmer's notebook and also his book Agile Software Development. It states, "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it."

The example he gives is that of the square and the rectangle. In geometry, they are both two dimensional figures with four sides and four 90 degrees angles and square is a just a type of rectangle in which the height and width are equal. Obviously, it makes sense for square to derive from rectangle. However, under certain circumstances, squares and rectangles exhibit different behaviour. Change the width of a square, and its height changes too; otherwise it is no longer a square. Clearly any method that changed the width of the rectangle base class would also need to know about the special case of the square, thus breaking the LSP. The breakage tells us that, in this context, the square should most definitely not be derived from the rectangle.

Bob's point is that we naturally classify things using the ISA relationship, i.e. a square 'is a' rectangle but we should be classifying them using the 'behaves as a' relationship. Does a square behave as a rectangle? Well, as we've already seen, there are circumstances when it doesn't.
© Robert Nicholls 2002-2024
The views and opinions expressed on this site do not represent the views of my employer.
HTML5 / CSS3