开发者

Java setter method convention (is it OK to overload setters?)

I have condition where the way i construct a string (finalValue) is based on the number of non null values i get in my input. So I was wondering if it is OK to over load the setter method for the string (finalValue) with one diff no of parameters and call them based on the values i get? Is this a bad programming practice?

public void setFinalString(String a){
   this.finalString = a;
}

public void setFinalstring(String a, String b){
   this.finalString = a + " --f " + b;
}

Or I can have the method to construct the finalString based on the inputs i get and then invoke the setter (no overloading here) for the finalString.

Pls tell me is it ok开发者_如何学JAVA to over load setters , suggest which is a better approach?

thanks


Yes, this is definitely a bad approach, a setter is always supposed to just set the passed parameter to the encapsulated private ivar.

The other logic should be somewhere else not in the setter, although it is sometimes accepted to have restrictions when you set the parameter in your setter i.e.

public setAge(int age) {
    if (age >= 0)
        this.age = age;
    else 
        this.age = 0;
}

That is as much logic as a setter should have, it definitely should never receive more than the value it is assigning to the ivar.


Perhaps you want to use a pseudo getter instead of setters?

private String a, b;
public String setA(String a) { this.a = a; }
public String setB(String b) { this.b = b; }
public String getFinalString() {
    if (a != null && b != null)
        return a + " --f" + b;
    if (a != null)
        return a;
    throw new Exception("Not enough parameters to construct final string");
}


If someone does not allow to override methods, he should put final keyword. It is about what you want to do and how you communicate ith other developers. Sometimes only way of communication is code and correct method signatures which dont allow misunderstandings.

Aproach depends on what you have, try to code in a sane way and think about how your classes should look like if some developer wants to use them and is not able to ask you questions.

If you are lucky (very lucky) he will approach same way :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜