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?

0

1 Answer 1

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());
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.