Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

java - Most appropriate place for bounds checking - constructor or setter?

Still relatively new to Java and I'm wondering which is the better way to handle this. I have a class constructor that takes a few parameters, and also in this class are public getters and setters:

private String name;
private Float value;

public MySampleClass(String theName, Float theValue) {
    setName(theName);
    setValue(theValue);
}

public void setName(String n) {
    this.name = n;
}

public value setValue(Float v) {
    this.value = v;
}

I'd like to do some bounds checking on this Float. It seems like the best place to put it would be in the setter:

public value setValue(Float v) {
    if (v < 0.0f) {
        this.value = 0.0f;
    } else if (v > 1.0f) {
        this.value = 1.0f;
    }
}

This code originally had the bounds checking in the constructor and again in the setter, which seemed redundant. I changed the constructor to call the setter and put the checks in there. Does that make more sense? Or am I violating some convention of which I am completely unaware?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling overridable methods from your constructor is a bad idea. Do something more like this:

private String name;
private Float value;

public MySampleClass(String theName, Float theValue) {
    this.name = theName;
    setValueImpl(theValue);
}

public void setName(String n) {
    this.name = n;
}

public void setValue(Float v) {
    setValueImpl(v);
}

private void setValueImpl(Float v) {
    if (v < 0.0f) {
        this.value = 0.0f;
    } else if (v > 1.0f) {
        this.value = 1.0f;
    }
}

This gives you the validation in both places and eliminates the calls to overridable methods. See this question for more on this.

Edit: If you plan on subclassing MySampleClass and want the validation setter available, declare it protected final instead of private.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...