I am a junior rails developer and was advised to use Class.find(id) to query the database instead of Class.find_by_id(id) which I previously had. The reason I was told is because the former would raise an exception while the latter would return nil. I realize this happens but I am wondering what the high level conceptual logic is for doing it this way. Why do I want the exception? Is this a rails standard where I would always prefer a method that returns an exception as opposed to nil?
Share
Nils are problematic as a return type in Ruby in general. There’s a great (paid) screencast by Gary Bernhardt that explains why you want to avoid returning nil from methods, but in a nutshell: when a method returns nil, and that nil gets passed up through a chain of method calls and something goes wrong somewhere, it can be extremely difficult to figure out where the actual problem occurred.
Say, for example, you have something like this:
and a method:
Now, if
MyModel.find_by_name('foo')returnsnil, that nil will be carried along without any errors until it actually has to do something. Say, insome_other_method, you actually try to call something onmodel, saymodel.save, you will get an error:The trace will carry you back up the method calls, but it will not mention the line that was actually problematic, where you assign
MyModel.find_by_name('foo')(which evaluates tonil) tofoo_model.You can imagine that in a real application, the code can be much more complex, and returning nil can make it much more difficult to figure out the source of an error.
An exception, in contrast, tells you immediately where the problem is, and the trace will go back to the line where it occurred. That’s one reason (there are others, I imagine) why in general, returning
nilis not a good idea.Hope that helps.