If I have multiple constructors in a class, how do I avoid duplicate code for those fields which are initialized identically for all constructors, or is this not preferable?
For example:
class ComparableThing<K extends Comparable<K>> {
private int someField;
private Comparator<K> comparator;
public ComparableThing() {
this.someField = 0;
this.comparator = Comparator.naturalOrder();
}
public ComparableThing(Comparator<K> comp) {
this.someField = 0;
this.comparator = comp;
}
}
Is there a way to avoid the duplicate code in initializing someField
, or is this duplicate code considered acceptable/preferable?