Sub topic 6
Validating and Computing Values Through Accessors
This chapter assumes you already know how to write class getters and setters and how to declare private # fields. Here you put the two together. The public accessor checks and cleans the input, and the private field holds the value that passed those checks.
The Gatekeeper Pattern
If a field is public, any code can assign anything to it. To prevent that, make the stored value private and expose it through a setter. Every write then goes through code you control. The setter decides what to do with the input in one of three ways:
- Reject the input by throwing an error.
- Normalize it by trimming, lowercasing, rounding, or converting units.
- Store the result in the private field.
A Worked Example
The Product class below validates and normalizes its name and price. It also exposes a computed, read-only priceWithTax.
const TAX_RATE = 0.2;
class Product {
#name;
#priceCents;
constructor(name, price) {
this.name = name; // runs the setter
this.price = price; // runs the setter
}
get name() {
return this.#name;
}
set name(value) {
if (typeof value !== 'string' || value.trim() === '') {
throw new TypeError('name must be a non-empty string');
}
this.#name = value.trim();
}
get price() {
return this.#priceCents / 100;
}
set price(value) {
if (!Number.isFinite(value) || value < 0) {
throw new RangeError('price must be a non-negative number');
}
this.#priceCents = Math.round(value * 100);
}
get priceWithTax() {
return Math.round(this.#priceCents * (1 + TAX_RATE)) / 100;
}
}
const lamp = new Product(' Desk Lamp ', 19.999);
console.log(lamp.name); // 'Desk Lamp'
console.log(lamp.price); // 20
console.log(lamp.priceWithTax); // 24
try {
lamp.price = -5;
} catch (err) {
console.log(err instanceof RangeError); // true
}
console.log(lamp.price); // 20 (the failed assignment changed nothing)Look at these details:
- The constructor assigns through
this.nameandthis.price, not throughthis.#name. This way a new object gets the same checks as a later assignment. - The internal representation (whole cents) differs from the public one (a decimal amount). Callers never see that choice, so you can change it later.
- The setter validates before it writes. When it throws, the object keeps its last valid state.
Computed Properties
priceWithTax has a getter and no setter. Its value is derived each time it is read, so it can never go out of sync with price. Storing derived values in a separate field leads to bugs. Every write to the source value then has to update the copy too.
When you assign to a getter-only property, the result depends on the strictness of the code doing the assignment. In strict mode or inside a module, lamp.priceWithTax = 1 throws a TypeError. In a sloppy-mode script, the assignment is silently ignored.
Common Errors
| Mistake | Consequence | Fix |
|---|---|---|
| Validating only in the constructor | Later assignments skip the checks | Put the checks in the setter and have the constructor call it |
| Writing `this.#field = arg` in the constructor | Invalid initial state | Assign through the public setter |
| Assigning first, validating after | A failed write leaves bad state behind | Validate, then assign |
| Getter returns an internal array or object | Callers change private state directly | Return a copy, such as `[...this.#items]` |
| Heavy work in a frequently read getter | Hidden performance cost | Cache it or expose a method instead |
Exercises
Exercise
Write a class Percentage with a private #value. Its value setter should accept numbers from 0 to 100 and round them to one decimal place, and throw a RangeError for anything else. Add a read-only fraction getter that returns the value divided by 100.
Show answer
class Percentage { #value; constructor(v) { this.value = v; } get value() { return this.#value; } set value(v) { if (!Number.isFinite(v) || v < 0 || v > 100) { throw new RangeError('0-100 only'); } this.#value = Math.round(v * 10) / 10; } get fraction() { return this.#value / 100; } } With new Percentage(42.37), value is 42.4 and fraction is 0.424.
Exercise
A Product constructor sets this.#priceCents = price * 100 directly, without calling the setter. What goes wrong when someone calls new Product('Pen', -3)?
Show answer
The object is created with a negative price of -300 cents, because the constructor skips the setter's validation. Assigning through this.price = price in the constructor would throw a RangeError instead.