I have often wondered about the implications of shortening code by assigning temporary variables with shorter names to data accesses with long names. It's best illustrated by an example (in Ruby, but not that it matters):
This long code is ugly, IMO:
# Trim the description to MAX_LENGTH characters followed by "..."
# if the description is MAX_LENGTH characters or longer
def shorthand_description
return (some_object.nested_hash.description.length >= MAX_LENGTH)
? "#{some_object.nested_hash.description[0..MAX_LENGTH]}..."
: some_object.nested_hash.description
end
This seems to be a lot more readable:
def shorthand_description
desc = some_object.nested_hash.description
return (desc.length >= MAX_LENGTH)
? "#{desc[0..MAX_LENGTH]}..."
: desc
end
Personally I almost always shorthand variables if the long access chain is more than about 20 characters and it's repeated. Is creating a variable only to make the code more readable acceptable? Does it depend on style guidelines for the language, or is it a language-agnostic concept?