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


Conditional before the call

def foo(thing)
  puts thing
end

if thing
  foo(thing)
end

Conditional within the call

def foo(thing)
  return unless thing
  puts thing
end

foo(thing)



Pros of 1:


Method is concise and easier to read
Method can assume input is valid
Obvious what's going on in calling code


Pros of 2:


Caller doesn't need to check condition every time the method is invoked
Calling code is cleaner and easier to read
Conditional is centralised in one location and not duplicated (DRY!)


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