100 words 003

I reviewed a pull request today. A method was called with a local variable, e.g.:

def log(msg)
  msg << ' ' + Time.now.to_s
end
message = 'message'
log(message)
puts message # prints "message 2017-01-23 22:15:41 +0000"

The log() method mutates the caller. The object that the local variable message points to has changed to the value set by the log() method. This is because Ruby passes-by-value, where the value is a reference.

Tom Dalling says:

Avoiding mutability by default is, in my opinion, a rule worth applying.

If a method is going to mutate the caller, indicate this by using an exclamation-mark/bang in the method name, e.g. log!(msg).