When did Ruby’s “beautiful, readable code” mantra take such a shitty turn? Or has it always been this bad and I just never noticed back in my “OMFG I LOVE RUBY” days?
It’s apparently poor practice (at least in many circles) to use “@” in front of instance variables.
This is supposedly bad:
class GoodbyeWorld def initialize(n) @name = n end def helpme # Using the instance var "@name", sir puts format("kill me now, %s!", @name) end end
You should expose methods instead of accessing vars directly. So this is better:
class GoodbyeWorld attr_reader :name def initialize(n) @name = n end def helpme # Oh, sorry, I'll stop using @name - using a function call instead, sir puts format("kill me now, %s!", self.name()) end end
Okay, I can see an argument for that. If we want
name to return something less static, we’re now certain all calls will go through whatever logic we have if we decide to define
name as some kind of custom method.
But then it’s also poor practice to prefix instance methods with “self”. And … it’s poor practice to call a method with parens unless they’re absolutely necessary. So this is the best way to do it:
class GoodbyeWorld attr_reader :name def initialize(n) @name = n end def helpme # Oh, sorry, too many parens and explicit use of "self". Fixed, sir. puts format "kill me now, %s!", name end end
In a 10-line example, no big deal (though I’d still call it garbage). But when you have a ton of code with modules being mixed, global scope being polluted by various includes, and an app written by multiple people who generally suck at programming (i.e., any given group of software developers), you end up with methods filled with identifiers you can’t easily track down. Are they variables or function calls? Are they part of this class? Something mixed in? Something from a parent class? Some global thing defined somewhere else? No fucking idea.
If you ever wonder why I would rather write 3x as much code in Go, this right here is one of the biggest reasons. I can look at Go code I haven’t seen in months or even a couple years, and tell at a glance all these little details. Scope is very well-defined. The program’s logic may be garbage, and following functions and types around can be a massive pain in the ass, but there is no time spent trying to figure out the origins of every fucking identifier.