![Et tu, Brute?]
Off with his head
Ruby developers have gone back and forth for ages as to whether to use
on their method calls. Why is everyone bickering? Can’t we all just get along?
My guess is that we can’t.
This argument is similar to that of the use of whitespace. Some people are picky while others are not; however, almost all have a very strong opinion.
This above all: to thine own self be true
I prefer to qualify all public instance method calls with
self.. I’m one to
lean towards being explicit versus implicit, and
self. helps me achieve this
goal. This also makes coworkers (or any other individual reading the code)
aware of whether the method call is an attribute defined by ActiveRecord or a
public instance method on the class. The reason this is an issue is because
local or block-level variables will never be prefixed with
self. - it’s much
easier on the eyes to be able to tell immediately whether you’re dealing with
one or the other.
Tempt not a desperate man
The explicitness of
self. may be construed as line noise. You may also be
asked why you don’t use Hungarian notation. Using
self. isn’t a naming
convention; it’s defining the receiver of the message explicitly. There’s no
misconception and you’re relaying intent very plainly by adding five characters.
This is the long and short of it
class User < ActiveRecord::Base before_save :sanitize_names def display_name return email if first_name.blank? [first_name, last_name].compact.join(" ") end protected def sanitize_names self.first_name = nil if first_name.blank? self.last_name = nil if last_name.blank? end end
The result, after everything is said and done, would be:
class User < ActiveRecord::Base before_save :sanitize_names def display_name return self.email if self.first_name.blank? [self.first_name, self.last_name].compact.join(" ") end protected def sanitize_names self.first_name = nil if self.first_name.blank? self.last_name = nil if self.last_name.blank? end end
Although there may not me much of a different to the casual reader, the second is, in my mind, worlds easier to comprehend.