Coding style showdown


#1

I’ve often not understood the following two coding styles and I am asking for some constructive feedback on them.

readOnly ALL THE THINGS!

I’ve seen this used everywhere. Anytime a computed property is used the readOnly() is added. I curious why it isn’t the default if it is important to always have it there.

foo: computed('bar', {
  get() {
    ...
  }
}).readOnly(),

I’ve asked and the only answers I’ve gotten is that the instructors at several Ember Bootcamps really push this style.

Destructuring hoop-da-loops

const {
  foo, bar, baz
} = this.getProperties(
  'foo', 'bar', 'baz'
);

Versus

let foo = this.get('foo');
let bar = this.get('bar');
let baz = this.get('baz');

This is used for small and large sets of variables. I don’t understand the const either but the first one happens a lot in our code while the latter seems to read better and provides flexibility such as offering defaults or NullObjects:

let foo = this.get('foo') || 'FOO';
let bar = this.get('bar') || {};
let baz = this.get('baz') || new NullObject();

I’m curious where these styles originate from and what others have to say about them.


#2

I don’t know much about the .readOnly flag - in general computed properties should be considered pure functions as much as possible, so maybe it’s an attempt to enforce that?

Regarding the destructuring part, I don’t think it needs to be a matter of one style or the other. I think either can be used as appropriate for the use case. If you need to set a default, break them apart. Otherwise, take advantage of destructuring. There isn’t any performance benefit that I know of to using the destructuring route - the Ember code for getProperties is literally a loop that calls get for each prop.

  ...
  for (; i < propertyNames.length; i++) {
    ret[propertyNames[i]] = get(obj, propertyNames[i]);
  }
  return ret;

As for const - some people like to use that to indicate the variable isn’t supposed to change. There are caveats, it isn’t a true constant unless it’s a simple value (and even then it only prevent reassignment). So it’s more something to communicate to others reading the code than it is for any other reason.