Constant abuse?

2020-04-02 02:22发布

I have run across a bunch of code in a few C# projects that have the following constants:

    const int ZERO_RECORDS = 0;
    const int FIRST_ROW = 0;
    const int DEFAULT_INDEX = 0;
    const int STRINGS_ARE_EQUAL = 0;

Has anyone ever seen anything like this? Is there any way to rationalize using constants to represent language constructs? IE: C#'s first index in an array is at position 0. I would think that if a developer needs to depend on a constant to tell them that the language is 0 based, there is a bigger issue at hand.

The most common usage of these constants is in handling Data Tables or within 'for' loops.

Am I out of place thinking these are a code smell? I feel that these aren't a whole lot better than:

const int ZERO = 0;
const string A = "A";

2楼-- · 2020-04-02 02:27

Abuse, IMHO. "Zero" is just is one of the basics.

Although the STRINGS_ARE_EQUAL could be easy, why not ".Equals"?

Accepted limited use of magic numbers?

3楼-- · 2020-04-02 02:28

That definitely a code smell.

The intent may have been to 'add readability' to the code, however things like that actually decrease the readability of code in my opinion.

4楼-- · 2020-04-02 02:28

You should have a look at some of the things at thedailywtf



Enterprise SQL

5楼-- · 2020-04-02 02:31

Am I out of place thinking these are a code smell? I feel that these aren't a whole lot better than:

Compare the following:

if(str1.CompareTo(str2) == STRINGS_ARE_EQUAL) ...


if(str1.CompareTo(str2) == ZERO) ...
if(str1.CompareTo(str2) == 0) ...

Which one makes more immediate sense?

6楼-- · 2020-04-02 02:32

Some people consider any raw number within a program to be a 'magic number'. I have seen coding standards that basically said that you couldn't just write an integer into a program, it had to be a const int.

7楼-- · 2020-04-02 02:33

If the zero indicates something other than zero (in this case STRINGS_ARE_EQUAL) then that IS Magical. Creating a constant for it is both acceptable and makes the code more readable.

Creating a constant called ZERO is pointless and a waste of finger energy!

登录 后发表回答