airbnb / ruby

Ruby Style Guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Constants

JohnReedLOL opened this issue · comments

Ruby style guide...

Use snake_case for methods and variables.
Use CamelCase for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.)
Use SCREAMING_SNAKE_CASE for other constants.

^ This is bad style because it promotes unnecessary use of mutable state, which is a source of future bugs. SCREAMING_SNAKE_CASE is really ugly, so people tend to only use it when they feel obligated to, i.e. global constants. But GoF said that coders should favor immutability over mutability (everywhere), not just for global constants.

SCREAMING_SNAKE_CASE is okay for global constants, but what about all the local constants? I would argue that using SCREAMING_SNAKE_CASE for all the immutable local state would uglify the code and would obfuscate the difference between global immutable state and local immutable state. I would argue for a trailing underscore for local constants (so as to differentiate them from class names).

Use snake_case for methods and variables ( def spectacular_flight, bengal_tiger = :tigger ).
Use Camel_Case
(with trailing underscore) for local constants (Bengal_tiger_ = :tiger).
Use SCREAMING_SNAKE_CASE for global constants._

I would also argue that snake case doesn't work well with the red and blue underlines in the IDE because the underlines make it hard to see the non-trailing underscores, but the important thing is that compared to other programming languages, Ruby has too much mutable state.

"ugly" is very subjective. I don't find SCREAMING_SNAKE_CASE ugly at all, and personally, I love seeing it all over the place because it conveys immutability - for both global and all local constants. (Note that a local immutable variable isn't a "constant", and thus would use snake_case)

Do you have data beyond your own experience that suggests that "people tend to only use it when they feel obligated to"? I've never encountered that motivation before, personally.

In addition, if your syntax highlighting doesn't work well with any given capitalization, that's a problem with your editor, and shouldn't inform a style guide - most editors don't have any issue with it.

Thank you for the suggestion. We're trying to keep this style guide largely consistent with idiomatic Ruby, and I've never seen Camel_Case_ (or uppercase first letter for any local, regardless of what comes after it) in all the Ruby projects I've worked on so I think it strays too far from the norm.

I also disagree with the contention that local mutable state is a source of future bugs, but even if I come to agree with it, the deviation from idiomatic is still too much.