Thursday, September 12, 2013

Setting Values in Java Enum - A Bad Idea

My Scala habits have made me create a stupid bug related to Java enums. In Scala, the concept of case classes is very neat and recently, I just confused enum in Java with what I sometimes do in Scala case classes.

I wrote an enum with a setter like:

    public static enum BlackVariateType {

        private double volSquare;
        public double getBlackVolatilitySquare() {
            return volSquare;

        public void setBlackVolatilitySquare(double volSquare) {
            this.volSquare = volSquare;


Here, calling setBlackVolatilitySquare will override any previous value, and thus, if several parts are calling it with different values, it will be a mess as there is only a single instance.

I am not sure if there is actually one good use case to have a setter on an enum. This sounds like a very dangerous practice in general. Member variables allowed should be only final.

No comments :

Post a Comment