Best practice for global constants involving magic numbers

前端 未结 5 1527
北海茫月
北海茫月 2020-12-17 21:11

To avoid magic numbers, I always use constants in my code. Back in the old days we used to define constant sets in a methodless interface which has now become an antipatter

5条回答
  •  庸人自扰
    2020-12-17 21:48

    Enum is best for most of the case, but not everything. Some might be better put like before, that is in a special class with public static constants.

    Example where enum is not the best solution is for mathematical constants, like PI. Creating an enum for that will make the code worse.

    enum MathConstants {
        PI(3.14);
    
        double a;        
    
        MathConstants(double a) {
           this.a = a;
        }
    
        double getValueA() {
           return a;
        }
    }
    

    Usage:

    MathConstants.PI.getValueA();
    

    Ugly isn't it? Compare to:

    MathConstants.PI;
    

提交回复
热议问题