A Compound Name Is a Code Smell
Join the DZone community and get the full member experience.
Join For Free
do you name variables like
textlength
,
table_name
, or
current-user-email
? all three are compound names that consist of more than one word. even though they look more descriptive than
name
,
length
, or
email
, i would strongly recommend avoiding them. i believe a variable name that is more complex than a noun is a code smell. why? because we usually give a variable a compound name when its scope is so big and complex that a simple noun would sound ambiguous. and a big, complex scope is an obvious code smell.
the meaning of life (1983) by terry jones and terry gilliam
the scope of a variable is the place where it is visible, like a method, for example. look at this ruby class:
class csv def initialize(csvfilename) @filename = csvfilename end def readrecords() file.readlines(@filename).map |csvline| csvline.split(',') end end end
the visible scope of variable
csvfilename
is method
initialize()
, which is a constructor of the class
csv
. why does it need a compound name that consists of three words? isn't it already clear that a single-argument constructor of class
csv
expects the name of a file with comma-separated values? i would rename it to
file
.
next, the scope of
@filename
is the entire
csv
class. renaming a single variable in the class to just
@file
won't introduce any confusion. it's still clear what file we're dealing with. the same situation exists with the
csvline
variable. it is clear that we're dealing with csv lines here. the
csv
prefix is just a redundancy. here is how i would refactor the class:
class csv def initialize(file) @file = file end def records() file.readlines(@file).map |line| line.split(',') end end end
now it looks clear and concise.
if you can't perform such a refactoring, it means your scope is too big and/or too complex. an ideal method should deal with up to five variables, and an ideal class should encapsulate up to five properties.
if we have five variables, can't we find five nouns to name them?
adam and eve didn't have second names. they were unique in eden, as were many other characters in the old testament. second and middle names were invented later in order to resolve ambiguity. to keep your methods and classes clean and solid, and to prevent ambiguity, try to give your variables and methods unique single-word names, just like adam and eve were named by you know who :)
Published at DZone with permission of Yegor Bugayenko. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
What ChatGPT Needs Is Context
-
Security Challenges for Microservice Applications in Multi-Cloud Environments
-
DevOps Midwest: A Community Event Full of DevSecOps Best Practices
-
Clear Details on Java Collection ‘Clear()’ API
Comments