Tip 40: Simplify Interfaces with get and set
Protecting class properties
You have the basics of classes. You can create instances, call properties, call methods, and extend parent classes. But it won’t be long before someone tries to alter a property you had no intention of exposing. Or maybe someone sets the wrong data type on a property, creating bugs because the code expects an integer, not a string.
Think about your
Coupon. It has a property of
price, which you initially set in the constructor. A user of the class can access the property on an instance with dot syntax:
coupon.price. So far, no problem. But because an instance of
Coupon is just an object, the user can also change the property:
coupon.price = 11.
In itself that’s not a big deal. But you’ll eventually hit a problem where
another developer (or, admit it, you yourself) innocently tries to set a value
other parts of the code may not expect. For example, what if instead of setting
price with an integer, you set it using a string? The change may seem
harmless, but because all methods expect an integer, the change could ripple
through the class, creating unexpected bugs.