Hello! Sorry for the noob question, but is it possible to use the condition in the setter? In the problem being solved, the resulting value must meet a certain condition, otherwise the default value must be substituted. I want to do this, but not sure if this is correct:

public void setHouseName(String houseName) { if (houseName.length()<4 || houseName.length()>20){ this.houseName = "House#" + collectorNumber; } else{ this.houseName = houseName; } } 
  • Well this is the usual methods ... so it can be - Alexey Shimansky
  • Of course you can and even need. For that they are, and the "empty" setters and getters as for me garbage! - JVic
  • @ 0xdb, corrected. - jayrumi
  • one
    There are very few setters / getters in well-designed classes. If you have a lot of them, then this is most likely a problem in design. - Mikhail Vaysman

2 answers 2

Yes, of course you can. Only this will be the setter that sets the value. Getter on the contrary, returns it

 public void setHouseName(String houseName) { if (houseName.length() < 4 || houseName.length() > 20) { this.houseName = "House#" + collectorNumber; } else { this.houseName = houseName; } } 
    1. Are you sure you getter from setter?
    2. In both it is possible, since these are just ordinary functions. Theoretically, for this and need.
    3. The code in question is not this.houseName = houseName; , because the assignment this.houseName = houseName; happens unconditionally. It is necessary to leave assignments only in the if'a branches, and remove the latter.
    • Yes, the latter is not necessary here. This is just a slip of the pen. Thank you for your comment. Now I will correct the code. - jayrumi