Naming convention for private/protected properties and methods


#1

Hello,

I couldn’t find any information about naming convention in Ember world for private/protected properties and methods.

export default Component {
  // Attributes passed into component
  firstName: null,
  lastName: null,

  // Private stuff...
  fullName: computed('firstName', 'lastName', function () {
    return get(this, 'firstName') + " " + get(this, 'lastName');
  }),
}

The problem here is that consumer could easily overwrite fullName with his own value without even noticing that it’s intended to be private only.

What’s the convention in Ember world to let my fellow colleagues know that this property is private or protected and it shouldn’t be set from outside?

I can think of a few

  • call readOnly() on computed property -> will throw an error (not applicable to all private stuff as no all private stuff is computed property)
  • use underscore _fullName -> which means I have to use underscore in template, but I guess that’s not a problem
  • use comment with @private attribute -> very easy to overlook

Do you have different naming convention for private and protected properties/methods?

Thank you


#2

This is one of the reasons we added @ arguments. The goal is to clearly separate “things from outside” from “things that are internal”. Once everybody is using @ arguments in both the consuming side and the calling side, it’s no longer possible to overwrite a component’s own internal properties with arguments (because fullName and @fullName are different things).

But yeah, your list is pretty good.

readOnly doesn’t really prevent a caller from stomping your property, it just prevents data from flowing upwards out of your component.

Underscores a pretty effective. Not pretty, but clear to readers.

I know there are some folks with thoughts about how to use TypeScript such that even in templates you would get type checking for component arguments. That would be wonderful and would let you use a compiler-enforced private.


#3

Not quite sure if I got you wrong, but trying to override a component property declared with readOnly macro throws Cannot set read-only property: https://ember-twiddle.com/af68966fe219264c32420fcd9cfb2828?numColumns=2&openFiles=components.my-component.js%2Ctemplates.application.hbs (Have a look into the console.)


#4

Oh yes, you’re right.

I was thinking of a different case (child classes replacing their superclass’s properties).


#5

I read this blogpost https://www.emberjs.com/blog/2018/04/13/ember-3-1-released.html but it’s not clear to me how it works and how to use it.

Should I use @ sign in computed properties to get passed attributes?

fullName: computed('@firstName', '@lastName', ...)

and in template

Hello {{@firstName}}, is your full name {{this.fullName}}?

Is it possible to do set/get on those attributes?

this.get('@firstName')
this.set('@firstName', 'Albert')

Thanks for clarifying :pray:t4: