Tip 40: Simplify Interfaces with get and set

In this tip, you’ll learn how to mask logic behind simple 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.

One of the major problems in JavaScript is that there are no private properties by default. Everything is exposed. You can’t control what the users of your class do with the methods or properties.

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 the 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.

Get hands-on with 1000+ tech skills courses.