2

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?

Eri.
  • 465
  • 2
  • 6
  • 14
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –  Jul 13 '13 at 21:01
  • This is not about how to compare strings, but where to put the statements... – Eri. Jul 13 '13 at 21:07
  • There is no such a difference between setter and getter methods. You should be missing something not related to setters getters. – erencan Jul 13 '13 at 21:16

1 Answers1

2

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.

0x6C38
  • 6,796
  • 4
  • 35
  • 47
  • Make sense, for instance my code example is working in the getter but not in the setter. Do you maybe know why? – Eri. Jul 13 '13 at 21:12
  • there no obvious reason for that, if you post the code maybe I can tell you – 0x6C38 Jul 13 '13 at 21:13
  • Ok that is actually everything I wanted to know, if there is no obvious reason I have to check my code again. Many thanks for your explanation. First I thought that doing it in the setter maybe was wrong but now I get it. – Eri. Jul 13 '13 at 21:16