Why is the use of a constant considered better programming style than the use of a literal?

假装没事ソ 提交于 2020-01-23 07:56:28

问题


Why is the use of a constant considered better programming style than the use of a literal? What is the exact advantage of the prior over the latter?


回答1:


One reason is to assist in maintenance. Let's say you're stuck in the dark ages and your graphic manipulation program works only with 1.4M floppy disks.

You get a request to handle the new-fangled 2.8M floppy disks and you think to yourself "Ha, I just need to search through the code looking for 1440 and replacing that with 2880. Simple, eh?".

Unfortunately, being a graphic program, 1440 is also the number of twips in an inch, so you find that after doing your massive global search and replace, not only can you handle the larger disks but all your images are the wrong size on the screen. D'Oh!

Now you have to go back and figure out which of those 1440 strings were for the disk size and which were for the image size.

If you had just developed your code like this:

#define TWIPS_PER_INCH 1440
#define DISK_SZ 1440

you could have made the change much easier, by just changing that constant in one place without affecting all other constants with the same value.

Short answer is that named constants make your life a lot easier. That really should be reason enough for using them.

Some extremists will insist that the only hard-coded constants you should ever have in your program are -1, 0 and 1 - some will go even further but we can discount the crackpots :-) I'm not quite to that point but I do think it's a good idea to avoid them as much as possible.

One thing I find amusing is people who do things like:

#define SEVENTY_TWO 72

I'm not exactly sure what they think they're gaining by that but I actually got that once in response to a comment I made in a code review about the hard-coded 72 (I can laugh about it now but I was none too happy in the second review meeting).


Another reason is to make the code more readable. Unless you have a mathematical background, you're going to be at a loss when you see a constant like 1.414 in your code. However, the symbol SQR_ROOT_OF_2 is likely to be much more understandable. It's the same with most other constants, like:

SECS_PER_DAY      86400
CUST_ADDR_LINES   7
INVALID_ID        -1
DAYS_PER_CENTURY  36524
PASS_LEVEL        63
MIN_REPUTATION    10000
MAX_LOAN_AMT      200000

Would you rather have code with those numbers on the right scattered throughout, or would you rather read code where the intent is better presented?




回答2:


Because the constant represents some concept, rather than the value of the concept.

For example:

x = 3.14 * 3 ^ 2;

vs

x = PI * RADIUS ^ 2;

The first is "just numbers", which could have any meaning. The second has concepts in the equation, making the intent clearer.




回答3:


It's simple - you can assign a constant once and re-use it many times. When you need to change it, you change the value once. If you use literals, you have to maintain all of them - potentially hundreds of long forgotten numbers or strings.

In addition, the constant's man imparts meaning that a literal may lack.




回答4:


  • Some constants change, such as the initial value of some variable or maximum number of something. Using an identifier allows you to change the constant everywhere it is used, just by changing the single declaration. Often the constant is used in only one place at first, but may be repeated in more places over time. Also, if you use an identifier, you have the option of changing the constant into a variable if you later need to be able to choose the value at runtime.
  • To act as documentation. For example if you see if (m > MONTHS_PER_YEAR) rather than if (m > 12) then you can infer that m represents a month. (I usually don't name all constants that are set in stone like MONTHS_PER_YEAR; instead, m should be named "month" so that the meaning of 12 becomes clear).
  • In the case of PI, to shorten the code, and allow you to alter its precision later (or to emphasize the "concept" over the number, as Will said).



回答5:


I think constansts are better becuase their values can change, so the change only need to be in one place. But overusing constants as in the example #define SEVENTY_TWO 72 is an indication that a person has a screw loose.




回答6:


Using constants is strongly linked to the concept of "magic numbers". Not the ones that identify files, but the ones that seem to have been determined by magic.

Consider the following code sample:

x = y * 100 / 2;

or even worse

x = y * 50;

How does anyone reading the code know what the intent of the author was?

But if you do it like this:

x = y * CENTS_IN_DOLLAR / NO_OF_PARKING_METERS;

it instantly becomes fairly obivous that ydenotes a sum of money in dollars and we're trying to split them evenly between two parking meters (forgive me for the extremely silly example).

Constants should convey purpose, and this is the most important thing to bear in mind: a constant that doesn't tell the reader what purpose its value has in the code is a bad constant. For the same reason, reusing constants for a different purpose is a terrible idea, even worse than not using any as it gives a false impression of understanding.

If you only want to remember one word about why constants are useful, I'd vote for "purpose".



来源:https://stackoverflow.com/questions/4351022/why-is-the-use-of-a-constant-considered-better-programming-style-than-the-use-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!