Ruby Voodoo

Deep dives into random corners of my favorite programming language.

8

OCT
2008

Readable Booleans

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 Rails 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.

In: Ruby Voodoo | Tags: APIs & Style | 2 Comments
Comments (2)
  1. Ciarán Walsh
    Ciarán Walsh October 8th, 2008 Reply Link

    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 :)

    1. Reply (using GitHub Flavored Markdown)

      Comments on this blog are moderated. Spam is removed, formatting is fixed, and there's a zero tolerance policy on intolerance.

      Ajax loader
  2. Tim Morgan
    Tim Morgan October 8th, 2008 Reply Link

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

    1. Reply (using GitHub Flavored Markdown)

      Comments on this blog are moderated. Spam is removed, formatting is fixed, and there's a zero tolerance policy on intolerance.

      Ajax loader
Leave a Comment (using GitHub Flavored Markdown)

Comments on this blog are moderated. Spam is removed, formatting is fixed, and there's a zero tolerance policy on intolerance.

Ajax loader