Most of my system’s class attributes are just text, but in this case it makes more sense to place this particular class’s attributes into one single hash (from a “keep the source code pretty” aspect). Basically, a list of attributes is returned, and instead of writing a bunch of static attributes for each one, I just loop over them and collect them into a hash.
Is it a good idea to name this particular attribute @contents_hash
, as opposed to @contents
? I assume that users may figure out pretty quickly that @contents.split ' '
will return a NoMethodError: undefined method 'split' for Hash
, but on first glance of the code, is it useful to know right away that this is a hash? Do you think it will make the implementation redundant to say @contents_hash.keys
?
2
I would only put the datatype in an identifier if it clearly adds value and clarity.
Nowadays, intellisense (or “on-the-fly code analysis,” as Jetbrains calls it) and type inference has pretty much eliminated the need for identifying types in your variable names. Write clear code in the first place, so that you don’t need to identify the type.
Ruby (and other dynamic-typed languages) don’t generally put the type in the name of variable, largely because that type could potentially change. That type of naming convention is generally seen more in statically-typed languages (namely, Visual Basic), because it’s a safer environment in which to do that (the variables can’t change types as easily), but it’s falling out of favor even there.
What happens if somewhere you have content = 'some string'
? Well, now, had you used content_hash
, the variable would be lying about its type. This makes things confusing.
Instead, think about naming things in a way that makes it more clear that the type is likely to be a hash. “contents” is pretty generic, and could mean either a string or a hash, but maybe “settings” or “attributes” would be a better choice, because “settings”/”attributes” has a connotation of being a collection of key-value pairs (a hash), or at least an array of values, without actually being tied to the exact type.
See also:
- Ruby style guide
- Duck Typing (technically applies to inheritance, but the idea applies here – if it looks and acts like a hash, then it’s probably a hash)