Hacker News new | ask | show | jobs
by Lio 3160 days ago
I like this joke, it kind of reminds me of the difference between `find_by_id` and `find` in ruby on rails.

In the former, if a result can't be found it will return `nil` but in the latter it expects the record to exist and so will raise an exception if it can't be found.

3 comments

Python: `Dict.get(k)` (`null`) vs `Dict[k]` (`IndexError`)
that sounds so backwards. `find_by_id` is a lookup, not a search; it seems implied to me that the ID should exist and if it doesn't that's an exception. Whereas `find` is a search and it's not atypical for search results to be empty.
Since I think rails 4 or earlier it's preferred to use `find_by(id: 4)`, but could instead be `find_by(email: "email@example.com")`, or even `find_by(first_name: "Franky', last_name: "Tomato")`.

IMO returning nil instead of an exception for the above is practical for me. Much easier to work with.

Having `find(4)` raising an exception is because you'll typical use it in your member actions for a controller where it's reasonable to want an exception if something can't be found.

It's just Rails being Rails (practical sometimes at the expense of possible interpretation of correctness). You do have to retain stuff like this in your head, but it becomes habit pretty quickly.

This begs the question of what the hell is the point of the bang convention e.g. find! in this case.
I've never seen `find!`. If that's a thing, then I have no idea why.

I've have found `find_by!` useful though. Say you want to raise an exception with `find_by!(email: "asd@asd.com")` or `find_by!(slug: "parameterized-string")` etc.

I've heard that joke once, but in C++