3 ms·
The advantage of using accessors is that your implementation can switch between static properties and computed properties and the consumers of your API don't ha
by tomdale 15y ago
The advantage of using accessors is that your implementation can switch between static properties and computed properties and the consumers of your API don't have to know which is which. This is called the uniform access principle and ends up being extremely useful.
For example, imagine you have an Store object that saves the tax rate:
Store = SC.Object.create({
taxRate: 0.0895
});
Since this is a static value, I don't technically have to use an accessor. But imagine my state implements a tax holiday, and so for one day per year, the tax rate is different. In Amber, this is a simple change:
taxRate: function() {
if (this.get('isTaxHoliday')) {
return 0;
}
return 0.0895;
}.property()
Instead of trawling my codebase to references for this property and changing them to method invocations, because everything goes through get(), I know the change will be transparent. It's this transparency that leads to very maintainable web apps.
Some people object to the extra method invocation, but I think the expressiveness it gets you is worth it. As soon as proxies land in JavaScript, we'll add support for them so you can use the dot notation and still get the same functionality.
- autarch 15y agoI don't think you really read what I wrote code-wise. I'm all for using accessors, that's why I wrote: var prop = model.prop() Note the parens there. I just like giving each accessor a unique method name as opposed to getting at all properties through a single get() method.
- tomdale 15y agoSure, but then you have to create a function for each property, even if it's a number or a string. Those bytes add up significantly in large applications. Additionally, specifying the property as a string allows you to implement "unknown property" handlers, which is another extremely powerful idiom.
- mbostock 15y agoThis might become more common when Proxy is supported more widely in JavaScript implementations. http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxie...