local constants vs comments

Zohar Peled - May 21 '20 - - Dev Community

Consider the following code (c#, but I hope readable for developers of other languages also):

bool IsCorrectType(int inputType)
{
    // 2 is the only correct type.
    return inputType == 2; 
}
Enter fullscreen mode Exit fullscreen mode

against the following code:

bool IsCorrectType(int inputType)
{
    const int correctType = 2; 
    return inputType == correctType;
}
Enter fullscreen mode Exit fullscreen mode

Which would you consider more readable, and why?

(of course, this is only a simplified example, actual code is more complicated)

For non c# readers:
// is be beginning of a line comment,
and the const int in the second code snippet is a local constant - the compiler replaces each occurrence of it with it's value - so performance wise these codes are equal.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player