Reusing constructors with destination instance fields

Suppose I have the following class that is trying 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 say that I do not want to use the builder for this class (to solve the problem).

So the question is:

Is there a way to achieve this behavior without removing the final modifier in epsilon and preserving 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); } } 
+4
source share
1 answer

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

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

Basically, you can get quite a few constructors that just pass in one “real” constructor that does all the actual work.

+7
source

Source: https://habr.com/ru/post/1302224/


All Articles