4 ms·
> A common counterexample to OO inheritance is the relationship between a square and a rectangle. Geometrically, a square is a specialisation of a rectangle: ev
by kccqzy 9y ago
> A common counterexample to OO inheritance is the relationship between a square and a rectangle. Geometrically, a square is a specialisation of a rectangle: every square is a rectangle, not every rectangle is a square.
Alternatively, you can argue that a rectangle is just a square with the additional freedom to vary the width and height independently. So in C++ syntax you would have:
class Square {
protected:
size_t width;
// No need to have "height" field because Square guarantees that height ==
// width.
public:
virtual size_t getWidth() const { return width; }
virtual size_t getHeight() const { return width; }
};
class Rectangle : public Square {
size_t height;
// A rectangle allows height to be different from width.
public:
virtual size_t getHeight() const override { return height; }
};
See? This makes OO hard because it's hard to decide which should be the subtype of which intuitively, and people get even more confused since the arrow is contravariant in its left argument and the relationship would sometimes appear reversed. There in fact is one correct answer but people often get it wrong. You need some serious appreciation of OO to know which.
Here are some more examples that can cause confusion. Suppose we have Reference (which can be read or written), ReadableReference (read-only) and WritableReference (write-only). From a purity perspective, should we have Reference inherit from both ReadableReference and WritableReference (ignoring OO languages that don't allow multiple inheritance), or should we have ReadableReference and WritableReference inherit from a single base class Reference? This kind of question frequently trips people up.
- acjohnson55 9y agoIn Scala, partial function is a subtype of function, even though it would seem like the opposite should be true, conceptually.
- kccqzy 9y agoThanks for the example. Yeah this is another case where people have trouble understanding subtyping relation and which type should be the subtype of which. And I agree with you that the opposite should be true conceptually, because if you ask yourself, "if a partial function is being demanded, can you use a function instead?" you might answer yes. Alternatively, think of a partial function conceptually as a function that returns an option type, i.e. in Haskell syntax type Function a b = a -> b type PartialFunction a b = a -> Maybe b and with the obvious addition that "b" is a subtype of "Maybe b", then we again conclude that function should be a subtype of partial function.
- acjohnson55 9y agoFor sure. And since all functions can throw exceptions, a partial function is just a function that just happens to throw a lot of them :)
- msangi 9y agoThis is interesting. I find that inheritance as a code reuse tool pushes developers in the direction of taking whatever class they have and tuck some new properties to a subclass. On the other hand, if you realise that a square is a rectangle with the same width and height, why should you bother at all with creating a new class? A new constructor (or an helper function) should be all you need
- kccqzy 9y ago> On the other hand, if you realise that a square is a rectangle with the same width and height, why should you bother at all with creating a new class? A new constructor (or an helper function) should be all you need What if you have a function that only knows how to operate on squares? Forcing it to accept Rectangles will be unnatural. Of course we can use just a single type Rectangle with two constructors, but inherently that's throwing information away about certain conditions we know to be true. Even in functional programs when we don't have inheritance, we still sometimes need conversion functions between related types and whether or not these use option types illustrates essentially the same idea: data Rectangle = Rectangle Int Int data Square = Square Int recToSq :: Rectangle -> Maybe Square -- may not succeed; like downcasting sqToRec :: Square -> Rectangle -- always succeeds; like upcasting Indeed, this is exactly what the "coercion semantics" in subtyping means: whenever S is a subtype of T, we can generate a total function from S to T. I believe this is also called "inheritance as implicit coercion" in https://www.sciencedirect.com/science/article/pii/0890540191900557 https://www.sciencedirect.com/science/article/pii/0890540191... Quoting from the abstract: > We present a method for providing semantic interpretations for languages with a type system featuring inheritance polymorphism. […] Our goal is to interpret inheritances in Fun via coercion functions which are definable in the target of the translation.
- jcelerier 9y ago> What if you have a function that only knows how to operate on squares? Forcing it to accept Rectangles will be unnatural then you write another function that does what you want with rectangles. I think that most of the problems with inheritance stem from unnatural obsession for code reuse such as this.
- stupidcar 9y agoThe deeper problem is that many domains cannot be modelled as hierarchical taxonomies, but only as ambiguous categories. This is a theory expounded by, amongst others, George Lakoff in his book "Women, Fire and Dangerous Things"[1] and elsewhere. Such cognitive categories are fuzzily defined, often overlap, and represent a collection of traits and properties that members of a category share some or all of. But different members can belong to the category to a greater or less extent, or be better or worse examples of it. E.g. both ostriches and sparrows are birds, but sparrows are usually considered a better example of the category birds. Like the process of developing scientific taxonomies, efforts to model these kind of domains using OO techniques frequently run into edge cases that defy concrete classification. E.g. can all birds fly? Clearly, flight is an extremely important trait of the class "bird", but we also recognise flightless birds as birds, which means objects can lack an important trait of a category, but still belong to it, albeit as a worse example. This is not just a theoretical problem. Imagine trying to invent a set of classes to model computing devices for an IT asset management system. What exactly constitutes a smartphone, vs. a tablet, vs. a laptop, etc.? It's easy to imagine the attributes and behaviors you might attach to these classes, but properly mapping every real world device onto them is extremely difficult. You are always going to get edge-case devices that straddle multiple classifications, or exclude some behavior that is assumed to be critical to devices of its type. The result is that systems trying to model such domains end up with a variety of problems: Some impose a rigid, but essentially arbitrary, taxonomy, with the result that users struggle to use it properly. Edge-cases require special, out-of-band handling, e.g. users understanding that the system cannot properly represent items of a particular type, and that you have to accept a misclassification, or misuse the system slightly in order to make it work. Some systems flatten and generalise the taxonomy into a single superclass, perhaps called "Device" in our example, that holds all the attributes and behaviors of all the former subclasses. This requires users to then interrogate objects of this generic type and essentially determine their "actual" type on an ad-hoc basis, with the result that they may be treated differently, or incorrectly, by different processes, depending on the heuristics that were applied in that case. And finally many systems just abandon the idea of internally representing the taxonomy in concrete terms at all. As edge-cases proliferate, and that idea that "every X is just a specialised case of Y", is taken to its conclusion, the concrete taxonomy dissolves and is replaced with a general taxonomical abstraction. A new, more flexible object system is implemented on top of the native object system, such that users of the system can define their own classes, at runtime. These systems will support tagging and multiple membership, and other devices for representing complex taxonomies. This solves the problem of representation, but only by abrogating responsibility for defining it entirely to users of the system. These users are then faced with the task of developing the taxonomy from scratch in userland. In an organisation where different departments need to agree on a common taxonomy, this process is often centralised, and a single simplified set of classes is presented to sub-users. But then edge-cases to this taxonomy start to emerge, and the process repeats itself. This is how layers of abstraction proliferate. [1] https://en.wikipedia.org/wiki/Women,_Fire,_and_Dangerous_Things https://en.wikipedia.org/wiki/Women,_Fire,_and_Dangerous_Thi...
- chrismorgan 9y ago> There in fact is one correct answer but people often get it wrong. You need some serious appreciation of OO to know which. Please enlighten me which one is correct, and I’ll happily argue that the other is in fact correct! (I think you’re going to say Square extending Rectangle is correct lest Rectangle break Square’s invariants, but I’m not certain. What language you’re operating in may influence the matter; for there can be very important differences in how different languages handle variance which can invert the answer. I’m a little rusty on this, though, because I haven’t had to actually worry about it for a few years since I last wrote Rust code where the variance of a type with respect to a generic parameter actually mattered, and for work I’m mostly writing JavaScript where it’s all fuzzy enough that you pretty much get to decide what is right and what is wrong!)
- JepZ 9y agoIf you want to argue about OO you should use Smalltalk. Many other languages use some shortcuts (often for performance reasons) which ignore central concepts of OO (e.g. 'everything is an object').
- fnl 9y agoGreat post. I would go as far as claiming "don't really mess with inheritance until you have not internalized the principles of co- and contravariance". Might be a bit extreme, but I see no way how you can safely navigate OOP without (see Java's famous problems with getting this wrong on container types...).
- JepZ 9y agoWell, the conceptual view is always first. So in fact a square is a subclass of a rectangle. Implementation comes second, and has to find out how much code sharing is possible.
- humanrebar 9y agoI prefer the data representation comes first, especially in a language like C++. Maybe you can represent 1000 squares with 1000 integers. If you need polymorphism on top of that, there are plenty of approaches without rearranging or copying the data to make it fit a type taxonomy.
- Ace17 9y agoYou reduced the "Square" class to a convenient implementation helper. Whatever type they choose to use, clients of your class hierarchy now only see one interface: getWidth/getHeight. And they can't make assumptions based on the type they see, as both "Square" and "Rectangle" might have "getWidth()!=getHeight()". So they must handle the generic "rectangular" case. So, for the client, there's absolutely no visible difference between a "Square" or a "Rectangle". Which means there's no point in dealing with two classes anymore : all client code will then take "Square" objects, and deal with them as geometrical rectangles.