2

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?

Nick Alexeev
  • 1,688
  • 2
  • 22
  • 36
asteele
  • 21
  • 2

1 Answers1

1

You can chain the constructors. Call a more general constructor from a more specific constructor. It's not uncommon.

class ComparableThing<K extends Comparable<K>> {
  private int someField;
  private Comparator<K> comparator;

  public ComparableThing(Comparator<K> comp) {  // more general constructor
    this.someField = 0;
    this.comparator = comp;
  }

  public ComparableThing() {
    this(Comparator.naturalOrder());
  }
}
Nick Alexeev
  • 1,688
  • 2
  • 22
  • 36