(no title)
EliAndrewC | 9 years ago
All kidding aside, a lot of our lodash code ends up looking something like this:
function (xs) {
return _(xs).pluck('foo').filter().value();
}
That code clearly expects that xs is an array of objects. However, we might occasionally end up with xs being undefined, or with xs being an array but one of the elements is null, etc.Most of the time, we want our function to just swallow those errors and return an empty array in such cases. This is exactly what lodash does, but if we tried to call xs.map(...) in that case we'd get an error. Similar caveats apply for grabbing the foo attribute if one of the array elements ends up being null or something.
For this reason, I recommend continuing to use lodash almost all of the time, even when there's a native Javascript method available.
sly010|9 years ago
That's exactly what I would expect. If only everyone always thrown an exception on any undefined, life would be so much better.
e28eta|9 years ago
Obj-C basically has the behavior GP wants: call a method on nil (aka: null) and it returns nil/false/0. It's possible to write concise & correct code that relies on this behavior.
Swift turns it into a fatal runtime error, and uses the type system to help prevent it from happening.
I think there's room for both (probably not in the same project though!). A lot of successful projects have been written in Obj-C, and some of them rely on the behavior of nil.
However, it's harder to maintain the code. You have to reason about whether nil is possible and does the code do the right thing, or did the original author forget to consider the possibility? It's really nice when the static type system forces the programmer to be explicit.
Having used both paradigms, I honestly don't know which I'd prefer for JS - especially considering it's lack of static typing. It might depend on whether I was writing application or library code.
madeofpalk|9 years ago
There are perfectly valid reasons why silently failing is OK.
jdd|9 years ago
smt88|9 years ago
No no no no. That's a silent failure and a bug. That means our code is doing something we don't intend or understand.
geofft|9 years ago
In many other cases, of course, the robust thing to do is to catch a failure early and prevent some code from executing before it can do more harm, and err on the side of the system doing nothing instead of it doing something wrong. But neither of these is a universal rule.
savanaly|9 years ago
shados|9 years ago
That being said, that was my first reaction too. Null safe code is so important. How you do it (be it with Flow, Lodash, whatever), that doesn't matter, but I do find myself leaning toward libraries over native when payload size doesn't matter too much because of this.
A combination of Flow, Ramda and Sanctuary (for Maybes) if you want to be a bit more niche can give some pretty amazing results.
nailer|9 years ago
Why not call it 'objects' rather than 'xs'?