FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I've noticed a tendency towards two styles of conditionally executing methods:

  1. Conditional before the call

    def foo(thing)
      puts thing
    end
    
    if thing
      foo(thing)
    end
    
    
  2. Conditional within the call

    def foo(thing)
      return unless thing
      puts thing
    end
    
    foo(thing)
    
    

Pros of 1:

Pros of 2:

Anecdotally, I've noticed that most people tend to lean towards the first style. Lately I've found my self leaning towards the second style, for the pros I've given above.

Thoughts? Any other advantages/disadvantages I've missed? Any other styles?

{ asked by u2622 }

ANSWER

I think that one of the pros you listed for style 2 - "Conditional is centralized in one location and not duplicated" is sufficient all by itself to tip the scale to style 2.

Non-duplication of code is a very powerful idea, particularly in a system under development. There is always the possibility that something will change. Duplicated code is very fragile, because of the possibility of overlooking one or more instances. Even if you don't overlook an instance, changing multiple instances of duplicated code is always harder than changing one single instance of non-duplicated code.

{ answered by Donald.McLean }
Tweet