DIP 1030--Named Arguments--Community Review Round 1 Discussion

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 7 22:57:01 UTC 2020


On Fri, Feb 07, 2020 at 10:28:27PM +0000, matheus via Digitalmars-d wrote:
[...]
> Hold your rant buddy I was just replying to your example :)

I know. But you struck a nerve. ;-)


> > > > 	myRange.process(2); // what does '2' mean?!
> 
> But of course seeing a code like:
> 
> > 	enum two = 2; // look, ma! I know how to name magic numbers!
> > 	myRange.process(two); // yay, no more magic numbers!
> 
> Would be totally nonsense to me too. On the other hand:
> 
> > 	myRange.process(nRetries);
> 
> For me would be ok and a standard where I work. And the IDE would give
> me the hint about the value of nRetries.

Fair enough. But it seems a bit onerous to have to write this:

	int nRetries = 2;
	myRange.process(nRetries);

when you could just write:

	myRange.process(nRetries: 2);


> Talking about magic numbers, well I had enough of it after diving into
> code like[1]:
> 
> > tempy = 0x80000000;
> > for(i=-131072;i<=131072;i+=(2048>>gride))
> 
> > plc = x1+mulscale12((2047-y1)&4095,inc);
> > i = ((y1+2048)>>12); daend = ((y2+2048)>>12);
> 
> And need to understand each number. :)

I see nonsense like this all the time. It's common practice in
"enterprise" code. It's one of the red flags that says "don't touch this
spaghetti code unless you can eat the consequences". My policy is to
stay away from such code unless you absolutely can't get out of touching
it.  And even then, touch as little as you can to get your job done, and
then get outta there pronto, before the fragile tower of cards that is
the code comes crashing down on your head. :-P

In this particular case, clearly the constants aren't just one-off
constants; they have a specific meaning and really should be refactored
into named constants instead.  So in this case, I'd say it's a *good*
thing to get rid of the magic numbers.

But I disagree with the hardline attitude of "there must be no integer
literals in your code outside of constant declarations", which is
apparently what some people actually believe.  In each case, a judgment
call must be made, and there is no one-size-fits-all answer.  As Walter
said once:

	I've been around long enough to have seen an endless parade of
	magic new techniques du jour, most of which purport to remove
	the necessity of thought about your programming problem.  In the
	end they wind up contributing one or two pieces to the
	collective wisdom, and fade away in the rearview mirror.

You cannot just take a rule of thumb like "avoid magic constants" as a
crutch to avoid the necessity of thought about your present programming
problem. Sometimes it makes sense, but sometimes it doesn't; it doesn't
make any sense to have a knee-jerk reaction "aaaaah, magic constant!"
every time you see a naked integer literal.


T

-- 
Obviously, some things aren't very obvious.


More information about the Digitalmars-d mailing list