r/programming • • Mar 26 '14

JavaScript Equality Table

http://dorey.github.io/JavaScript-Equality-Table/
809 Upvotes

331 comments sorted by

View all comments

Show parent comments

0

u/moor-GAYZ Mar 27 '14

For user-defined types, you're on your own. By default they're all truthy, but you can't rely on that since someone might subclass you and implement non-default boolean semantics.

Using if foo with classes which do not provide useful boolean behavior (such as datetime objects) is at best poor style and at worst a violation of substitutability since it would interfere with subclassing.

When I write Python, my attitude to this is "their fault, then". If someone subclasses my stuff and adds a nonsensical __nonzero__/__bool__, their code would not work and it would be their own fault.

Of course when I want to test if something is None in particular (because, for instance, I said so in my function specification), I don't take the shortcut. But when I want to test "truthiness" I do just that too, and expect the caller to give me an object that implements that properly, if it does implement it.

The problem with datetime is that it accidentally provides a wrong boolean behaviour (and it's our problem because it's in the standard library).

1

u/NYKevin Mar 27 '14

When I write Python, my attitude to this is "their fault, then". If someone subclasses my stuff and adds a nonsensical __nonzero__/__bool__, their code would not work and it would be their own fault.

This is ridiculous. You can't possibly know that no subclass will ever need boolean behavior.

1

u/moor-GAYZ Mar 27 '14

If someone subclasses my stuff and adds a nonsensical __nonzero__/__bool__

2

u/NYKevin Mar 27 '14

What if they add a perfectly sensible __bool__ that nonetheless is incorrect in the context you wrote if foo? For instance, one that makes the class truthy or falsey based solely on data which was not part of the original class.

→ More replies (9)