Another Concise Code Example

- 2008-04-26 15:54:09

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.

3 Comments on Another Concise Code Example

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

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

  3. 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!


About You

Comment