Why make router private?

2.3k Views Asked by At

In the Angular 2+ (4) routing tutorial, it shows to make the router a private member, e.g:

constructor(
    private router: Router, // <- router is private
    private heroService: HeroService) { }
    ...
) {}

But it doesn't provide any explanation as to why router is private here. Having it private makes it harder to test, so what is the reason for it being private? Is it just best-practice, or is there some security implication of having it public?

Also, specifically, how to test routing, that the right routes are navigated to in different circumstances? The tutorial does not mention testing router/routes at all?

3

There are 3 best solutions below

0
On BEST ANSWER

Adding private, public, or protected implicitly adds a class-level field where the passed constructor parameter is assigned to.

This is a TypeScript feature for less boilerplate.

You can now access the passed value using

someMethod() {
  this.router...
}

instead of

class MyComponent {
  router:Router;

  constructor(
    router: Router, // <- router is private
    private heroService: HeroService) { }
    ...
  ) {
    this.router = router;
  }

  someMethod() {
    this.router...
  }
}

If there is no specific reason to make it public or protected, private is the right option. This is what they did.

0
On

Encapsulation. Make your fields private and functionality public. The client which uses your class in this case, need to know only what it can do, not how it do.

There are 3 access levels in TypeScript, public, private, protected. These keywords are supported only in Typescript level.

If you make your variable/function private, it will not be visible outside the class.

If you make your variable/function public, it will be visible outside the class.

If you make your variable/function protected, it will be visible only in the class itself and any class which inherits that class.

0
On

This is hardly particular to the router in this specific example… in OOP in general, the question is always "is this supposed to be accessed by outside code as part of the public interface of this class?" Are you ever expecting router here to be exposed and accessed from anywhere else like ctrl.router? If not, then it's only prudent to keep it private. Limiting the exposed public interface to only the really necessary parts makes it easier to figure out what uses what, and refactor it later as necessary since no external code is bound to it.