Readable Booleans

Posted 2 months ago in Ruby Tutorials and Ruby Voodoo.

There's a great little trick you can do to improve the readability of your code. A common problem is dealing with methods that have a boolean flag arguments. Here's an example I ran into just today in a Rail application:

def rating_stars(..., clickable = false)
  # ...
end

The problem with this is that you typically see calls like this scattered around the application:

<%= rating_stars(..., true) %>

Would you know what true did there if I hadn't shown you the name of the variable first? I didn't. I had to go hunting for that method definition.

Ironically the opposite problem, a magical dangling false, is much more rare in my experience. That's typically the default for these kind of arguments and it just makes more sense and reads better to leave it out.

Anyway, the point is that we can typically improve the ease of understanding the common case. Remember that in Ruby false and nil are false while everything else is true. That means that truth is very loosely defined and we can pass a lot of things for our boolean flag value. For example, after looking up the method and understanding what was needed, I chose to call it like this:

<%= rating_stars(..., :clickable) %>

My hope is that might save a future maintainer a trip to the method definition to understand the call.

I've used that trick in quite a few situations now. To give another example, FasterCSV's documentation encourages user code to pass :headers => :first_row instead of just :headers => true. That has the advantage of being more self-documenting as well as leaving me room for possible expansion to the API.

CiarĂ¡n Walsh added 35 minutes later:

If you need to pass another type when its purpose is not clear (e.g. false, or a number), you can use the slightly less attractive method of assigning to a throwaway variable:

print_something("Foo", rows=5)

Just make sure that the variable name isn't something that might be used :)

Tim Morgan added 44 minutes later:

This is awesome! Seems so obvious now. Why didn't I think of that?

Add Your Thoughts

You can use Markdown in the body of your comment to format text and make links.

Note that I reserve the right to edit any content you post here. I typically exercise this right to fix formatting issues. All posts must be approved so spam will never be seen on these pages.

Author:
URL or Email (optional):
Body: