Are setter methods only used to set the value of attributes as it is passed as argument? Can we write some validation logic before assigning the value to the attributes?
问题:
回答1:
Yes, validation logic is definitely acceptable.
It should be noted though that if you have extensive validation you might want to extract this to a specific validator service. But for simple validations you can safely do this.
The entire idea behind using getters & setters is so nobody will have direct access to your fields. If you just wanted to set/get the value, you can make them public
.
Instead, we use setters to validate the incoming data and see if it complies with the rules we set.
This concept is also called "Encapsulation", a cornerstone of Object-Oriented Programming.
回答2:
Yes, you can add validation logic in your setter attributes before assigning the values. In fact, you must do it if it is possible that unwanted values may be sent to the setters.
回答3:
It is actually encouraged to validate the input (check whether it fits your data abstraction) to your setter method, so yes you can.
回答4:
Sure. You can include a validation. It is acceptable, but not neccessary. You just have to take into account that if you don't validate it then any values will try to get set to the variable (meeting the data type requirements).
Basically if you have
public void setNickname(String nick)
{
this.nickname = nick;
}
and you want to validate it you can either do it inside the setter - for example
public void setNickname(String nick)
{
if(nick.matches("[a-zA-Z]+"){ // only letters
this.nickname = nick;
}else{
// react
}
}
or outside of the setter before using it
if(nick.matches("[a-zA-Z]+"){ // only letters
account.setNickname(nick);
}
or you can use a method to validate it or even a separate validator class. There are a lot of possibilities.
You don't have to be afraid of developers being dazzled by this, like some say here.
回答5:
Sure, there's nothing wrong with making setters only accept valid values.
回答6:
As long as you do not modify other fields of class it is correct to validate.
You should also consider removing setters and using constructor with valitation or builder in Joshua Bloh version
回答7:
There is absolutely nothing stopping you from doing any kind of other operation inside a setter of a property. You could do anything from validation to setting the value of some other property etc. etc. Thats not to say you should however. Use your good judgement and common sense to decide what to put in there. If the setter is bulked out with innumerable lines of code then you should question your program structure...