Quantcast
Channel: My name is Justin Kohnen, and I’m a Geek.
Viewing all articles
Browse latest Browse all 28

Developer Tip: Avoid random numerical constants

$
0
0

There always comes a time when we just need to use a single number or set of numbers in our code…. but please avoid typing something like:

if (permissionID == 3){
// do something
}

Instantly I thinking

What is 3?

Is there a 1 and 2?

Is there documentation somewhere that can help?”

You can add a comment, that would be a bit helpful. But I believe a better solution is either an Enum or Class of constants. These solutions make your code more readable, and give more context around what “3” is.

Enum:

enum Permissions : int{
    None = 0,
    Read = 1,
    Write = 2,
    FullControl = 3
}
 
// .....
 
if (permissionID == (int)Permissions.FullControl){
// do something
}
Class of Constants:
publicstaticclass Permissions {
publicstaticconstint None = 0;
publicstaticconstint Read = 1;
publicstaticconstint Write = 2;
publicstaticconstint FullControl = 3;
}
 
// .....
 
if (permissionID == Permissions.FullControl){
// do something
}

Obviously these aren’t the only solutions… simply making a variable with a descriptive name might be enough…. but DO NOT just type a constant in the middle of your code.


Viewing all articles
Browse latest Browse all 28

Trending Articles