angular.io
angular.io copied to clipboard
Document the fact that underscores are acceptable for backing fields
As @wardbell has mentioned when you have a backing "field" for a public getter/setter, it's handy to prefix it with an underscore. Just to repeat his example:
private _foo;
get foo() { return this._foo; }
set foo(value: any) {
console.log(`${this._foo} changed to ${value}`);
this._foo = value;
}
Can that be added to the style guide?
I would be interested to know why some are giving this the thumbs down. Is there another, perhaps better, way to have a backing field with a getter/setter? How do you currently do it?
I see, understand and feel the problem. but using underscores only for backing fields gives a style incosistency so probably thats why you get thumbs down
what would be the recommended way then?
This is a serious issue I think.
Fact 1: Sometimes you want to have a private field with a public getter and/or setter. Otherwise using getter/setter would rarely make sense at all.
Fact 2: You cannot have the same name for the getter/setter and a field. Otherwise using this.field=val in the setter or "return this.field" would result in an endless loop.
If you accept both facts you have to accept that you are sometimes required to have different names for a field and a getter, even though they might return the same value.
So you have to rename either the field or the getter/setter.
I see two options
A) prefix private fields with _ (all of them for consistency sake) B) uppercase getter/setter
With A) already being used by a lot of developers.