Most appropriate place for bounds checking - constructor or setter?

后端 未结 2 1926
既然无缘
既然无缘 2020-12-17 05:32

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 p

相关标签:
2条回答
  • 2020-12-17 06:08

    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.

    0 讨论(0)
  • 2020-12-17 06:24

    For fairly simple data checks, such as your example, then yes, it makes the most sense to do the validation in the setter. However, if the validation for theValue also depends on theName (or on other things), then it would probably be worthwhile to perform the validation in the constructor (or on a private method that the constructor calls).

    0 讨论(0)
提交回复
热议问题