3 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 linkdd 5y 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.
Well yes and no.
A square and a rectangle are two kind of objects that have some common properties.
In Math, for an object to belong to a set, it must have the properties described by the set.
- Squares is the set of polygons with 4 sides of the same length and 4 right angles.
- Rectangles is the set of polygons with 4 sides and 4 right angles.
- Diamonds is the set of polygons with 4 sides of the same length.
So yes, it's difficult to represent this relationship with inheritance. But no, in OOP, you should not consider those properties as data on a class, but more like a trait/interface.
Your functions should take as input shapes implementing the expected traits/interfaces.
Then what is a shape? It's a collection of points. But a point can be 2D, 3D, n-D. Here you would still not use inheritance but generics.
Usually, I only use inheritance to specialize configuration, for example:
class Foo {
constructor(options) { ... }
}
class Bar extends Foo {
constructor() {
super({ some: 'options' })
}
}