Monday, July 22, 2013

Calling Overridable Methods from the Constructor

NetBeans will warn you not to call an overridable method from your constructor, and for good reason ...

public class PlayerCharacter implements DailyCycle {

    private static final int MAX_MOVES_REMAINING = 10;
    private static final int NEW_MOVES_PER_DAY = 3;

    private int movesRemaining;

    public PlayerCharacter() {
        newDay(); // WARNING
    }

    @Override
    public void newDay() {
        movesRemaining += NEW_MOVES_PER_DAY;
        if (movesRemaining > MAX_MOVES_REMAINING) {
            movesRemaining = MAX_MOVES_REMAINING;
        }
    }

}



What I Do...

I'm not really sure how other people handle this, but like to make a local version of the method (CTRL-SHIFT-M in NetBeans)...

 

public class PlayerCharacter implements DailyCycle {

    private static final int MAX_MOVES_REMAINING = 10;
    private static final int NEW_MOVES_PER_DAY = 3;

    private int movesRemaining;

    public PlayerCharacter() {
        newDayLocal();
    }

    @Override
    public void newDay() {
        newDayLocal();
    }

    private void newDayLocal() {
        movesRemaining += NEW_MOVES_PER_DAY;
        if (movesRemaining > MAX_MOVES_REMAINING) {
            movesRemaining = MAX_MOVES_REMAINING;
        }
    }

}

This not only solves the warning, but actually solves the problem. The object is no longer allowing subclasses to inject out-of-sequence code into the constructor by overriding a method.

 How do other people handle this? Is there a standard pattern?

No comments:

Post a Comment