6 ms·
Writable Getters
- RedShift1 6y agoScrolling through this page on mobile feels ropey, what's going on there?
- torh 6y agoSame on a Mac (not the M1 though)
- the__alchemist 6y agoIt scores 29/100 on Google Page Speed Insights. It cites a huge DOM, and large amount of third part content.
- eyelidlessness 6y agoI don’t want to come off too harsh, so I’ll preface that I respect the author and mean all of what follows constructively. With that said, this seems like a recipe for debugging nightmares. Getters and setters already make life difficult, hiding statefulness and complexity in a way that’s not apparent at the call site (you don’t even know it’s a call site!). Adding magic where sometimes a value is computed and sometimes it’s not amplifies those problems. Maybe my FP is showing, but all of this could be much more easily accomplished with plain value type data structures and functions. Computed values can be derived either at construction time (ideal, fewer nullish properties and less chance of passing incomplete values off to something that expects them to be complete) or by passing the structure to a function (or calling a method if you must, but here `this` is just an implicit argument to allow access to other properties of the structure). Replacing a computed value is as simple as constructing a new value structure with the value set explicitly. All of that is a lot easier to reason about (in terms of just reading the source to see what it does), almost certainly has better performance characteristics, and definitely makes concurrency less complex. These principles work very well in a general FP environment, but they can be applied to great benefit even in more imperative environments like JS.
- astrobe_ 6y agoWithout the "getter syntactic sugar": let lea = { name:"Lea verou", getId:function() { return this.name.toLowerCase().replace(/\W+/g, "-");} }; lea.getId() // lea-verou lea.getId=function() { return this.name; } lea.getId() // Lea Verou "syntactic sugar causes cancer of the semicolon" -- A. Perlis That said, I don't use JS and I agree it still looks like a bad idea, although this is not too heretic in a prototype-based-like language.
- eyelidlessness 6y agoI’m on mobile so forgive any syntax mistakes, but I’m talking more along the lines: const createLea = (data) => ({ ...data, id: ( data.id ?? data.name .toLowerCase() .replace(/\W+/g, '-') ), }); No mutation, no getters (function or implicit), dead simple to use, dead simple to reassign (just call the function again with the same data but provide a new `id` and super easy to understand at a glance (easier with types, but I digress). > prototype-based-like language One of the benefits of the approach I describe is you’re no longer working in a prototype based language. I mean, of course you are, but you don’t have to care. Edit: even on mobile I couldn’t stand the formatting. Edit 2: since I mentioned performance in my original comment, I’d add that there are two benefits here (one real, one possible with JITs): getters and setters (and anything with Object.defineProperty) perform worse than regular values; if you program in this style, the JIT has an opportunity to recognize that your values are generally immutable and optimize object construction e.g. with the spread operator as persistent data structures the same way FP languages do.
- drivingmenuts 6y agoJust seems like a bad idea - violating the idea of a getter and increasing complexity. Why have a getter in the first place? The proper place for this mess is the setter.
- eyelidlessness 6y agoWhy have either? Why even set a value more than once except as an optimization?
- Jarred 6y agoChanging the prototype of objects after they've been initialized causes deopts for JIT compiled code. Its convenient, but you probably can't use this pattern in performance-sensitive code.
- memling 6y agomy first programming job out of school involved working on a simulator with replay scenarios. a subtle bug arose due to what I assume was an optimization in which whenever a getter was called the value was incremented. during replay it would skip steps. it was not well documented. ever since I've avoided mutating getters.
- recursive 6y agoIt seems to me that you could achieve all of this much more simply by just coalescing (`??`) the mutable value to the default calculation inside the getter.
- stareatgoats 6y agoInteresting ways to stretch an objects capabilities but I would likely use a class for stuff like this, in which case the problem would be trivial to solve, in a highly legible way. I'm probably missing something since the author is a renowned author, and I'm just a dabbler. What am I missing though?
- recursive 6y agoI don't think you're missing anything. This is a one liner without any weird stuff. I've never heard of the author FWIW. let lea = { name: "Lea Verou", get id() { return this.explicitId ?? this.name.toLowerCase().replace(/\W+/g, "-"); }, set id(val) { this.explicitId = val; } }; console.log(lea.id); lea.id = 'lv'; console.log(lea.id);
- ivan_ah 6y agoExactly what I was thinking! I've used this computable-valye-but-overridable-with-explicit-value pattern a couple of times, and so long as you stick to a good naming convention it works great.
- lambda_obrien 6y agoI think if you want this type of thing, some sort of optics would be best, like a lens or a prism. Those are kind of designed for this use case.
- arunix 6y agoPerl has had this for a long time. Tagging a getter with ":lvalue" will make it assignable, even usable with the increment operator: pirl @> sub hats : lvalue { my ($self) = @_; $self->{hats}; } @var = (); pirl @> $obj = bless {} @var = ( bless( {}, 'Shell::Perl::sandbox' ) ); pirl @> $obj->hats @var = ( undef ); pirl @> $obj @var = ( bless( {}, 'Shell::Perl::sandbox' ) ); pirl @> $obj->hats = 1 @var = ( 1 ); pirl @> $obj @var = ( bless( { 'hats' => 1 }, 'Shell::Perl::sandbox' ) ); pirl @> $obj->hats @var = ( 1 ); pirl @> $obj->hats++ @var = ( 1 ); pirl @> $obj->hats @var = ( 2 ); pirl @>
- Arainach 6y agoIf the author is reading this, the random angles in the background colors are fairly distracting and give no benefit to the article or the site. Just because you can do something doesn't mean you should.
- wffurr 6y agoTo say nothing of the scrolljacking...
- 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.
- deleted 6y ago[deleted]
- janpot 6y agoI find the following version more intuitive: const lea = { name: "Lea Verou", _id: null, get id() { return this._id || this.name.toLowerCase().replace(/\W+/g, "-"); }, set id(v) { this._id = v; } }