4 ms·
> A pattern that has come up a few times in my code is the following: an object has a property which defaults to an expression based on its other properties unl
by md224 6y ago
> A pattern that has come up a few times in my code is the following: an object has a property which defaults to an expression based on its other properties unless it’s explicitly set, in which case it functions like a normal property. Essentially, the expression functions as a default value.
Having a dynamic default value makes sense, but instead of having the object reconfigure itself on the fly, why not design a single virtual field that intelligently chooses between two distinct sources of data? For example, you could write a class like this:
class MyObject {
#customFoo;
get foo () {
return this.#customFoo ?? this.#getDefaultFoo();
}
set foo (val) {
this.#customFoo = val;
}
#getDefaultFoo () {
// dynamically generate and return foo value
}
}
That way you could get a dynamically created value up until a custom value is set, with the option to switch back to the dynamic default simply by setting the field to null or undefined.
Also, I'm not sure if you were implying that it's a good thing, but the concept of "properties which execute code to produce side effects when they are get or set" seems a bit risky to me, especially the "get" part... it can make it very difficult to reason about the state of a system when simply accessing a property on an object has side effects. Obviously side effects don't need to be avoided at all costs, but IMHO it's best if they only occur during explicit function calls.