Search code examples
angulartypescriptencapsulation

Typescript private properties encapsulation conventions


Question: What is the best practice for naming private properties in Typescript and should one as a rule create a “get and set” for that property?

Reading the following link gave me pause to what I thought would be a good practice for coding Typescript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines

I understand his qualifier to his coding guideline that this is not a prescriptive guideline, however, his convention on naming private properties brings up questions in my mind on proper encapsulation and use of private properties in Typescript. The convention I have been following is to name the private properties with the prefix of underscore and then create a get and set that I use to assign or get the value from that property. Back in Anders’ Delphi days that convention is what made it a property and not just another variable. That property gave it characteristic that allowed for tooling.

Example:

…
private _progress: IImportInfo[];
…
get progress(): IImportInfo[] {
  return this._progress;
}

set progress(value: IImportInfo[]) {
  this._progress = value;
}
…

So from an html file you would get the values from the property as such:

<li *ngFor="let item of progress">

However, you could access it as such:

<li *ngFor="let item of _progress">

So access to the private variable from the outside is allowed. The encapsulation nature you would normally get with a private variable does not exist, however, there is some value in adhering to encapsulation rules (IMO). However, the purpose in asking this question is not about “my opinion”. I would like to know what more experience angular/typescript developers feel is a best practice in dealing with Typescript private properties. Better yet a link to a site (with credibility) of a “best practice” for dealing with private properties.

Thanks in advance for any help on this issue.


Solution

  • Found the answer I was looking for:

    https://angular.io/guide/styleguide

    Properties and methods Style 03-04 Do use lower camel case to name properties and methods.

    Avoid prefixing private properties and methods with an underscore.

    Why? Follows conventional thinking for properties and methods.

    Why? JavaScript lacks a true private property or method.

    Why? TypeScript tooling makes it easy to identify private vs. public properties and methods.