3.1.9 How to Use Logic in a Property

Properties can contain logic to check if we need to return a specific value or if we need to assign a value based on a particular condition.


This example with focus on the code below and the Rating property.

Let's say that you are tasked with ensuring that the value of the private rating field is not assigned to anything below 0 or above 5. The code below would work, but it's redundant and prone to breaking.

What we can do instead, is add a conditional in the setter of the Rating property that checks the incoming value.

Now if we try and assign the Rating to 400, the conditional will catch it and send an alert instead.