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
? all three are compound names that consist of more than one word. even though they look more descriptive than
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
, which is a constructor of the class
. why does it need a compound name that consists of three words? isn't it already clear that a single-argument constructor of class
expects the name of a file with comma-separated values? i would rename it to
next, the scope of
is the entire
class. renaming a single variable in the class to just
won't introduce any confusion. it's still clear what file we're dealing with. the same situation exists with the
variable. it is clear that we're dealing with csv lines here. the
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.