Skip to content

Chapter 2 nit: in geometry, a square is a rectangle #39

@davidhbrown-uri

Description

@davidhbrown-uri

Maybe this is just me, but the examples used to demonstrate inheritance demonstrated in Chapter 2 are bugging me a little. The code is fine, but in plane geometry, "A square is a degenerate rectangle", but a rectangle is not (necessarily) a square.

So, these examples, while of course they're completely true for this particular code as written, made me a little worried that they might at least momentarily confuse students by contradicting what they've learned in math class:
console.log(sq instanceof Rectangle); // false

This one -- not in the Safari ebook but found here in github in Chapter 2 / classes.js -- seems "worse" because this particular instance of rectangle does have unequal sides:
console.log(re instanceof Square); // true

I do understand that from a computer science perspective, what you've got is perfectly correct. Even if JavaScript used structural typing instead of nominal typing, it would work. (A Square has a width property. A Rectangle has width and height properties. A Square does not have a height property, so it is not a kind of Rectangle; a Rectangle does have a width property and so it is usable as a Square.)

Well, having typed all that, I'm thinking I'll treat this mild cognitive dissonance as a feature rather than a bug and if it even comes up in class tomorrow, use it as an opportunity to discuss how type and inheritance in programming is subtly different from type and kind-of in other contexts.

So, I guess this isn't really much of an issue, but if you wanted to add a footnote to a third edition about type in JavaScript vs. math, it might save a few head scratches here or there. Thanks for listening :-)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions