Re: Avoiding NPEs caused by indirect call
Royan wrote:
abstract class AbstractModel {
public AbstractModel() {
indirectCall();
}
private void indirectCall() {
setSomeValue(new Integer(1));
}
public void setSomeValue(Integer value) {
firePropertyChange("someProperty", null, value);
}
As Lew said, the chained call from the constructor is the problem. Never
ever do this. Calling any "foriegn" method too (like "indirectCall()" )
is broken because you don't know what they will call. If they call a
public, overriden method (which happens here), then you could be in a
lot of trouble.
Joshua Bloch describes almost the exact code you have with a big "Don't
Do This!" sign next to it. It's Item 17: Design and Document for
Inheritance or Else Prohibit It, in Effective Java 2nd edition.
A couple of classic solutions: use composition instead of inheritance.
Use a static factory (maybe with a Strategy Pattern to "plug in" the
exact Model you want).
Composition would use something like the Decorator Pattern. Use a
concrete class, DefaultModel, instead of an abstract class
AbstractModel, and wrap the new class around the default one.
But we kinda don't have enough info to help you out of this, it's very
much a design issue. "indirectCall" is the problem, you can NEVER do
this and expect it to work well. It must go. What are you really
trying to do here?