Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write validation logic in setter methods?

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?

like image 954
Mac Avatar asked Dec 04 '13 14:12

Mac


1 Answers

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.

like image 189
Jeroen Vannevel Avatar answered Sep 21 '22 07:09

Jeroen Vannevel