Wednesday, September 11, 2013

Developer Tip: Avoid random numerical constants

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 Permissions : int{
    None = 0,
    Read = 1,
    Write = 2,
    FullControl = 3
// .....
if (permissionID == (int)Permissions.FullControl){
    // do something
Class of Constants:
public static class Permissions {
    public static const int None = 0;
    public static const int Read = 1;
    public static const int Write = 2;
    public static const int 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.

No comments:

Post a Comment