guides:programstyle:constants
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| guides:programstyle:constants [2020/07/24 11:49] – wikiadmin | guides:programstyle:constants [2022/08/02 11:59] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 20: | Line 20: | ||
| </ | </ | ||
| - | Unless otherwise instructed, | + | At times the same constant may be given multiple names. |
| + | |||
| + | Acceptable Example: | ||
| + | <code c++> | ||
| + | const int MAX_ITEMS | ||
| + | const int PRICE_BREAK = 20; | ||
| + | |||
| + | ... | ||
| + | |||
| + | if (itemCount > MAX_ITEMS) { | ||
| + | ... | ||
| + | } | ||
| + | |||
| + | if (price > PRICE_BREAK) { | ||
| + | // the price was over $20, so give the customer a discount | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Unacceptable Example: | ||
| + | <code c++> | ||
| + | const int MAX_ITEMS = 20; | ||
| + | |||
| + | if (price > MAX_ITEMS) { | ||
| + | // the price was over $20, so give the customer a discount | ||
| + | ... | ||
| + | } | ||
| + | </ | ||
| + | Note this is a very bad use. If the user decided to change MAX_ITEMS, a new bug would be introduced into the code. | ||
| + | |||
| + | In the last example, a programmer might be tempted to employ the following definition | ||
| + | <code c++> | ||
| + | const int TWENTY = 20; | ||
| + | </ | ||
| + | |||
| + | This is unacceptable for multiple reasons. | ||
| + | * TWENTY is no more informative than 20. | ||
| + | * If the value of the constant changed, the programmer might be tempted to produce the following totally unacceptable code | ||
| + | * <code c++> | ||
| + | const int TWENTY = 35; | ||
| + | </ | ||
| + | |||
| + | Unless otherwise instructed, single | ||
| + | |||
| + | The following is probably not necessairy | ||
| + | <code c++> | ||
| + | const int FIRST_FIELD_WITDTH = 20; | ||
| + | const string FIRST_PROMPT = "Enter your Age"; | ||
| + | ... | ||
| + | |||
| + | cout << setw(FIRST_FIELD_WIDTH) << FIRST_PROMPT << endl; | ||
| + | </ | ||
guides/programstyle/constants.1595591394.txt.gz · Last modified: 2022/08/02 11:59 (external edit)