From: Peter Zotov Date: 2012-04-19T14:59:01+09:00 Subject: Re: When are numbers NOT Magic? Example. Greg Willits писал 19.04.2012 09:30: > (snip) > > Each value is displayed in only one place in the application. So > there's > no incentive to create a constant to prevent redundant literals. > > The precision is not something the user can choose. The application > must > hard code the displayed values, because the precision is meaningful. > So > there's no incentive to have a variable. > > The software has a generic method to render a floating point number > as a > string with thousands separators and with a specified precision. > > SomeClass#float_as_thousands_with_precision(value, precision) > > Which would get used something like: > > <%= float_as_thousands_with_precision(volts, 1) -%> > > > <%= float_as_thousands_with_precision(amps, 2) -%> > > > <%= float_as_thousands_with_precision(watts, 2) -%> > > > I contend, those are NOT magic numbers. > > Using the above definitions (and others I found like them), such > numbers > do not need constants because: > -- each number is a single instance (no redundancy) > -- each number is independent from the other (no shared cause & > effect > on precision) > -- each number's purpose is very clear from from both the function > name > and argument name (no need to clarify purpose) > > I know somone out there will say, "well, why not make a constant for > them? What does it hurt?" > > I say, why do it? It's more code to maintain with no benefit. If > people > can justify not making constants for clearly varying purposes of > using 1 > in code just because it's a 1, then I contend this is even a more > justifiable case to not bother with a constant. > > OK, that's my exhaustive argument. > > What say ye? Do these require constants? Are they magic numbers? I would just put a comment at the top of the file explaining the nature of these numbers. It's enough. Constants for magic numbers are essentially inline comments which also add another layer of error proofing. -- WBR, Peter Zotov.