Can I write validation logic in setter methods?

后端 未结 7 1061
自闭症患者
自闭症患者 2020-12-09 17:49

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条回答
  •  温柔的废话
    2020-12-09 18:19

    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.

提交回复
热议问题