Method return value should always be of same type

Posted Over 11 years ago. Visible to the public.

One of the main source of bugs and complexity in the code is when a functional method (that we expect to return a value) return different values under different circumstances.

For example, we ruby programmers have a bad habit of returning nil from a method when certain condition is not fulfilled else return an Array or Hash. That just makes the calling code unnecessary complex and error prone because then it has to do different checks.

Bad Practice:

def bad_method(param)
  return unless param == 'something'
  [1,2,3]
end

Good practice:

def better_method(param)
  return [] unless param == 'something'
  [1,2,3]
end

def better_method(param)
  return {} unless param == 'something'
  {:a => 'b'}
end

Now in the bad_method case caller always has to do the type check and in the better_method case since it always returns the same type of object, it will work flawlessly as long as you call the right method on the returned type.

However, this is not always possible in practice if the method returns a object that can be present or absent, i.e. ActiveRecord finder methods. Though there are other ways to counter that which I would not dive in yet.

Nasir Jamal
Posted by Nasir Jamal to HouseTrip Deck (2012-09-04 08:58)