function frob(foo) {
return (foo && foo.ary || [])
.map(...)
}
Even though I know everything that will call frob exists and has ary, that doesn't mean it won't change or work otherwise... one of the things I like about how shorting works in JS... though the "?" conditional null thing in C# is pretty damned close.I'll do other methods that will return an appropriate value, or null. In this way, if you can be defensive in your own code, you aren't the one called when someone hands you garbage.
Just like an HTTP server shouldn't crash because someone sends it data that should return a 4xx response.
It's best to make it impossible to call your function with the wrong kind of thing, but Javascript doesn't have a type system. Still though, if their code has gotten into a nonsense state, better to throw an exception (or whatever the language-standard way of handling errors is) than silently carry on. Otherwise they can spend up hours debugging their filtering logic wondering why it's started filtering everything out, when in fact the server they were calling into has started sending 1-element responses as not an array which your code then silently changes into an empty array.
> I'll do other methods that will return an appropriate value, or null. In this way, if you can be defensive in your own code, you aren't the one called when someone hands you garbage.
If you propagate garbage you're part of the problem. Defensiveness goes hand-in-hand with fail-fast.
> Just like an HTTP server shouldn't crash because someone sends it data that should return a 4xx response.
Right but if your query was malformed you should get a 4xx, not a 200 with no results. (This is one reason I think it's actually a bad idea to use 404 for when there's no item with that ID - it makes it hard for the client to tell the difference between "I called the API wrong" and "I called the API correctly but there are no results").