Question

I want to know where it it is recommended to put logic such as if statements, shall I do it in the setter or in the getter? For example, when I tried to do this in the setter it was not working:

if ("female".equals(gender)) {
   this.gender = "girl";
}

but it is working when I do it in the getter, and then I just return gender; and everything is as it should. So why was this statement not working in the setter?

Was it helpful?

Solution

There is no fixed rule for judging whether its best to put the logic in the getter or the setter (or neither). You'll have to decide depending on your application.

In general I'd recommend doing it in the getter as the gender might never get requested, in which case you'd have wasted an insignificant amount of processing power and ram if you did it in the setter.

Also the logic might be attached to other fields that may not have the same value at the time you set the gender as opposed to when you request it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top