2

I have the following abbreviated class:

public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player() {
        position = new DoubleDuple(0, 0);
        momentum = new DoubleDuple(0, 0);
    }

    public Player(double xPos, double yPos) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(0, 0);
    }

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    }
}

With the fields being listed as final, I can't just have each more complicated constructor call each simpler constructor, since the final field would then be assigned twice; which isn't allowed.

If though, I removed the final modifier from the fields, I could change the last constructor to:

public Player(double xPos, double yPos, double xMom, double yMom) {
        this(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
}

Which I find neater. In this example, it's not much of a change, but in situations where there are more fields that have defaultable values, it would be nice to not have to repeat myself in each constructor (DRY).

Questions:

  • When dealing with final fields, is there any way to not repeat myself in each constructor?
  • I'm asking this to abide by the DRY (Don't repeat yourself) principal. Should I be thinking this way?
8

The way I usually do it is to code only the last constructor, and then make the simpler constructors delegate to the most complete one, by providing default values. So, taking your example, I'd so it like this:

public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player() {
        this(0, 0, 0, 0);
    }

    public Player(double xPos, double yPos) {
        this(xPos, yPos, 0, 0);
    }

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    } 
}
  • Ahh! I'm embarrassed I didn't think of that. Thank you. – Carcigenicate Aug 9 '15 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.