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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
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
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
and you want to validate it you can either do it inside the setter - for example
or outside of the setter before using it
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.
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.
Sure, there's nothing wrong with making setters only accept valid values.
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.