Talking to Yourself Is Bad, mmkay?

October 20, 2008

A lot of languages encourage talking to yourself. OO PHP code is sprinkled with `$this->foo_method();`. In some languages it's necessary. Ruby isn't one of them. ```ruby class Foo def bar # Why are you talking to yourself?! @thingy = self.foo end def foo "QUUX!" end end ``` That `self.` is doing absolutely nothing. You can drop it entirely: ```ruby class Foo def bar @thingy = foo end def foo "QUUX!" end end ``` This is a trivial example, but it makes a real difference across a larger codebase. Less noise, easier to read, fewer characters to trip over. Give it a try -- your code will look less like it's having a conversation with itself. There's one caveat though: you *do* need `self` when calling a setter method. Without it, Ruby thinks you're assigning to a local variable: ```ruby class Foo attr_accessor :thingy def bar # This assigns to a local variable, NOT the attribute. thingy = foo end def foo "QUUX!" end end ``` ```ruby class Foo attr_accessor :thingy def bar # This calls Foo#thingy= as intended. self.thingy = foo end def foo "QUUX!" end end ``` So the rule is simple: skip `self` for reading, keep it for writing. Your future self (pun intended) will thank you.
Questions or thoughts? Get in touch.