I seem to be lacking enough coffee to make me see the following problem clearly.
Imagine I have a class with two constructors and several fields. One constructor is a no-arg constructor and one field depends on another. The other constructor takes an injected value for one of its fields. Example:
public class Practice {
private final int n;
private final char c;
private final Map<String, String> m;
private final Set<String> s;
public Practice() {
this.n = 0;
this.c = 'a';
this.m = new HashMap<>();
this.s = m.keySet();
}
public Practice(Set<String> s) {
this.n = 0;
this.c = 'a';
this.m = new HashMap<>();
this.s = s;
}
}
My question: how do I remove the duplication of code between the two constructors?
First failed attempt:
public Practice() {
this(new HashMap<>(), new HashMap<>().keySet());
}
public Practice(Set<String> s) {
this(new HashMap<>(), s);
}
private Practice(int n, char c, Map<String, String> m, Set<String> s) {
this.n = 0;
this.c = 'a';
this.m = m;
this.s = s;
}
Of course, this fails because the no-args constructor creates two separate Maps instead of one.