Another Concise Code Example

April 26, 2008 4:54pm | 5 Comments | , , and

This is just another example showing how I refactor code down to its bare minimum. The reason why I do this so much (and indeed I think why ruby is so easy to read compared to other languages) is because it makes my code more readable and less of a bugger to pick up after a while.

class Page
    attr_accessor :parent_id

    def old_parent
    # The returns aren't needed here in ruby, but in other
    # languages using this logic block you would require
    # the returns, so I left them in here.

    if self.parent?
      return Page.find( self.parent_id )
    else
      return false
    end
  end

  def parent
    return Page.find( self.parent_id ) if self.parent?
    false
  end

end

old_parent and parent return exactly the same, but one is 2 lines compared to 5 and easier to read.

Update: Ciaran pointed out that the Page.parent method would only ever return false. Added the return statement to it to fix the bug.

Comments

Do you have to return false? Will nil do? It will for many comparisons.

If so:

def parent
  Page.find(self.parent_id) if self.parent?
end

Or if false is necessary:

def parent
  self.parent? ? Page.find(self.parent_id) : false
end

This strikes me as one of those rare opportunities when a ternary makes it read better.

Put newlines in as necessary there. Gotta love blog systems ;-)

Heh yeah, its markdown parsed, so just indent with a tab or 4 spaces for code listing.

And yeah, returning nil probably would work just as well, but I prefer to explicitly state that its returning false, rather than relying on knowledge of ruby to figure out that its returning nil. (If I took the `false' out of there that is.)

And a ternary probably would make it read better yes, not often they make code more legible!

Leave a Reply