views:

56

answers:

2

Ruby's duck-typing is great, but this is the one way that it bites me in the ass. I'll have some long running text-processing script or something running, and after several hours, some unexpected set of circumstances ends up causing the script to exit with at NoMethodError due to a variable becoming nil.

Now, once it happens, it's usually an easy fix, but it would be nicer if I could predict these better, or at least handle these types of errors more gracefully. Sorry for the vagueness of the question, but this type of error just happens too often to me and I wonder if there's a good way to avoid it.

Is there some best practice related to these kinds of "type errors" for Ruby?

A: 

What about Object.nil?

Francisco Soto
Sure, but usually if an object is nil when I expected it to be a string or something, it means there was some problem earlier on that was unanticipated. Anticipating these problems is the hard part, not dealing with nil values that you know are going to occur.
ehsanul
+3  A: 

Look up Design by Contract. It's useful in many programming paradigms, but it's particularly useful when you don't have a compiler to help you catch these sort of errors, of forbidding particular sorts of values for a parameter.

In essence, DbC allows you to make an assumption about a parameter. It allows you (in all but one place) to skip the mundane checks that guarantee this assumption to hold.

wilhelmtell
Very interesting, and addresses my question well, thanks. However, is it really worth the overhead? Seems like it would almost be just as well to switch to a strongly typed language. I see there's an (unmaintained) Ruby library though, so it's definitely worth a look.
ehsanul