views:

55

answers:

1

Let's suppose that I have the following class which tries to be immutable

    public class Computation {

    private final Operation operation;
    private final double epsilon;

    public Computation(Operation operation) {
        this.operation = operation;
        //Default value
        epsilon = 0.01;

    }


    public Computation(Operation operation double epsilon) {
        this(operation);
        //Won't compile as epsilon is final and is set by the other constructor
        this.epsilon = epsilon;
    }
}

And, for the sake of the question, let's assume that I do not want to use a builder for this class (which would solve the issue).

So the question is:

Is there a way to achieve this behaviour without removing the final modifier to epsilon and keeping the two constructors?

That is, without doing something like

       public class Computation {

        private final Operation operation;
        private final double epsilon;

        public Computation(Operation operation Double epsilon) {
            this(operation);
            this.epsilon = (epsilon == null) ? 0.01 : epsilon;
        }
    }

and without using a builder

   public class Computation {

    private final Operation operation;
    private final double epsilon;

    private Computation(Builder builder) {
        this.operation = builder.operation;
        this.epsilon = builder.epsilon;

    }


    public static class Builder {

    private final Operation operation;
    //Default value
    private double epsilon = 0.01;

    public Builder(Operation operation) {
        this.operation = operation;
    }

    public Builder epsilon(double epsilon) {
         this.epsilon = epsilon;
         return this;
    }

    public Computation build() {
        return new Computation(this);
    }

}
+6  A: 

Yes - reverse the logic so that your constructor with fewer parameters calls the one with more:

public Computation(Operation operation) {
    this(operation, 0.01);
}

public Computation(Operation operation, double epsilon) {
    this.operation = operation;
    this.epsilon = epsilon;
}

Basically that way you can end up with quite a few constructors which all just delegate to one "real" constructor which does all the actual work.

Jon Skeet
I can't believe i missed that! Thanks, great answer!
Lombo