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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With