angular.io icon indicating copy to clipboard operation
angular.io copied to clipboard

Document the fact that underscores are acceptable for backing fields

Open battmanz opened this issue 8 years ago • 4 comments

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?

battmanz avatar Jan 25 '17 14:01 battmanz

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?

battmanz avatar Feb 04 '17 16:02 battmanz

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

denu5 avatar Mar 16 '17 14:03 denu5

what would be the recommended way then?

FrancescoBorzi avatar Jun 03 '17 18:06 FrancescoBorzi

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.

eun-ice avatar Nov 02 '17 15:11 eun-ice