Hacker News new | past | comments | ask | show | jobs | submit login

The spirit of the advice is mostly correct. However, there are reasons to use numeric literals in code. One is the PRNG example given downthread. Another is one I recently wrote.

I have some code where I needed to calculate what the 1st percentile of a list of numbers was. Since it doesn't make a lot of statistical sense to calculate a 1st percentile of fewer than 100 numbers, I inserted a condition like

    if len(numbers) < 100:
        # skip the calculation
and included a comment stating that 100 is explicitly not a magic number here. By that, I meant that you'll never want to change this 100, so, why bother obfuscating it behind a name?

It's perfectly readable, if you understand why the calculation is skipped in the first place. If you don't understand why the calculation is skipped, giving it a name like TOO_FEW_NUMBERS_TO_CALCULATE_1ST_PERCENTILE isn't really going to give you much insight into why the calculation is skipped, anyway.




You'd name it MINIMUM_NUMBERS_FOR_1ST_PERCENTILE (your name was for the entire if).

To me "if len(numbers) < MINIMUM_NUMBERS_FOR_1ST_PERCENTILE" still reads better and requires me not to need to refer to comments, which I fall back on when I do not immediately get the code.

So maybe the risk is not lowered, but readability is still improved.

(Oh, and I wonder what do you return for a list of all equal numbers when there are more than a 100? If it's that number, why would suddenly going from 100 to 99 change that? ;)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: