Search code examples
javaprogramming-languages

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 to over load setters , suggest which is a better approach?

thanks


Solution

  • 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.