4 ms·
In a statically typed language, restricting if conditionals to just booleans is the approach I like the most: simple and safe. On the other hand, in dynamic la
by ufo 11y ago
In a statically typed language, restricting if conditionals to just booleans is the approach I like the most: simple and safe.
On the other hand, in dynamic languages, where you can pass anything to conditional I think that treating 0 as falsy is very error prone. For example, its very common to use conditionals to implement default values:
function foo(name){
name = name || "default name";
}
In this setting, having 0 and "" act as falsy is a bug waiting to happen. On the other hand, having 0 act as truthy might confuse you a bit the first time you come across it but its an easy fix (just write x != 0 instead) and its not very likely to hit you when you don't expect it.
- JoshTriplett 11y agoIf your language has something like "None" or "null", then you should be checking against that to implement a default, rather than checking a truth value. After all, what if you wanted to implement a boolean parameter with a default value? Personally, I'm a big fan of languages with a "Maybe" type for this kind of thing.
- deleted 11y ago[deleted]
- ufo 11y agoThe `||` pattern is super common in a bunch of languages though and to code it with a `== null` test you would need to expand it to a full blown ternary operator name != null ? name : "default name" Some languages have a "null-coalescing" operator you can use in these cases but its a niche thing. (And I agree with you on the Maybe thing but, as I said previously, 0 in conditionals is not a problem when conditionals have to be boolean)
- JoshTriplett 11y agoMy point is, you should be checking for null or None or equivalent, rather than boolean false; once you do, 0 being false is no more or less of a problem than false being false.
- Someone 11y ago"Some languages have a "null-coalescing" operator you can use in these cases but its a niche thing." I see that not as niche, but as a fairly recent invention, or at least one that recently is becoming popular. IMO, C#'s ?? is superior to reusing binary operators. Advantages are that it looks more like the ternary operator, and that it doesn't require adding implicit conversions to boolean to your language.