Can I write validation logic in setter methods?

感情迁移 提交于 2019-11-28 09:58:36

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.

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.

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

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.

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

Marcin Szymczak

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

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!