4 ms·
Implicit coercion is often a source of bugs. Some languages simply mandate that you be explicit about your intent. It can be slightly more verbose, but you gain
by sgk284 12y ago
Implicit coercion is often a source of bugs. Some languages simply mandate that you be explicit about your intent. It can be slightly more verbose, but you gain clarity and reduce ambiguity.
With implicit coercion, the programmer must mentally keep track of how values get coerced (are negative numbers truthy? are empty strings? empty lists? empty objects?). Different languages have different answers for all of these things. As a result, I prefer to always be explicit.
If you've never seen the WAT?[1] talk, I suggest watching it. It has some great examples of type coercion gone wrong in Ruby and JS.
[1] https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat
- spankalee 12y agoBeing explicit is great, but it doesn't prevent a library from defining it's own boolean coercion rules. The Angular team, for instance, has defined toBool() (which they use in directives like ng-if) like this: bool toBool(x) { if (x is bool) return x; if (x is num) return x != 0; return false; } It treats true and non-zero numbers as true, and everything else (including null) as false.