Can I write validation logic in setter methods?

2020-02-05 07:29发布

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?

7条回答
Anthone
2楼-- · 2020-02-05 07:57

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-05 08:02

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.

查看更多
闹够了就滚
4楼-- · 2020-02-05 08:03

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.

查看更多
beautiful°
5楼-- · 2020-02-05 08:08

Sure, there's nothing wrong with making setters only accept valid values.

查看更多
时光不老,我们不散
6楼-- · 2020-02-05 08:11

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.

查看更多
欢心
7楼-- · 2020-02-05 08:12

It is actually encouraged to validate the input (check whether it fits your data abstraction) to your setter method, so yes you can.

查看更多
登录 后发表回答