Eric D. Schabell: A 'Ruby best practice' - return values

Tuesday, December 2, 2008

A 'Ruby best practice' - return values

Over on the wonderful Ruby blog 'On Ruby' they are holding a contest requesting that one post a best practice from another language or community and how it translates into Ruby. It just so happens there is one that I have personally applied to all my Ruby programming even though it is not a Ruby convention!

Return values in Ruby, where are they?
It really bothers me that code can become unclear or obscure by not communicating very simple facts, like what a method is returning. A good practice used in Java is to return a 'results', meaning one keeps the return value of a method stored in a variable named 'results'. It can be a String, Boolean, or whatever.

Ruby is one of my favorite languages right now, but handles return values for methods very differently than languages like Java. Ruby does not require an explicit 'return' statement, but can return the last executed statement results by default. This can be confusing.

Discovering what this return value might be can be more time consuming that is necessary and is immediately taken care of by simply supplying a 'return' statement. Cost is nothing, results are clarity. I provide an example from my current running project, AbTLinux:

##
# Cleans up this packages source build directory.
#
# RETURNS:  boolean - True if the completes successfully,
# otherwise false.
##
def remove_build
  puts "Removings build..."
  if ($REMOVE_BUILD_SOURCES)
      buildSourcesLocation = "#{$BUILD_LOCATION}/#{srcDir}"
       
      if (!File.directory?(buildSourcesLocation))
        return true
      end

      if (!FileUtils.rm_rf buildSourcesLocation, :verbose => true )
        return false
      end
  end
   
  return true
end