Code Complete* recommends that methods validate the arguments they
receive. The author went on to say that in a 1984 study, researchers
discovered that miscommunication between routines caused 39% of the
programming errors observed. The idea is that, if we check our
arguments before using them, bad data won’t flow through undetected,
causing even vaguer problems later on. Lucky for us, Ruby checks the
number of arguments received against the method definition – finding
many of these problems at the time they’re written. But checking
that the arguments make sense are still our responsibility. Should
we do it? Is it too much overhead for too little gain?
From the Rails source:
def select_tag(name, option_tags = nil, options = {})
content_tag :select, option_tags, { “name” => name, “id” =>
name }.update(options.stringify_keys)
end
The arguments to select tag are really easy to screw up. Adding code
to validate them would add four or five lines to this terse method.
Plus it would probably need a few helper methods just to remain
readable. But it would also prevent programmers from wasting huge
amounts of time hunting for why their browser rendered a bad select
box. The argument for adding validation is really strong for any non-
trivial project, but does it ruin Ruby’s elegance?
What do you think? Do you usually validate your arguments?
- Michael J.
- Code Complete is a book on software construction by Steve McConnell.