0
\$\begingroup\$

I have some code like this

  ngOnInit(): void {
    this.activatedRoute.url.subscribe(() => {
      const token = this.activatedRoute.snapshot.queryParamMap.get('token');
      const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage');
      if (token) {
        localStorage.setItem(AuthenticationStorageKey, token);
        if (redirectPage) {
          this.router.navigate([redirectPage]);
        } else {
          this.router.navigate(['']);
        }
      } else {
        this.router.navigate([`/error/404`]);
      }
    });
  }

What I does not like is that I have too many IF and ELSE, anybody knows some better solution, thanks?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Defaults & Ternaries

There is nothing wrong with statements.

However Javascript and most C like languages allow a wide variety of branching styles.

For example you can default the navigation, and use a ternary ? (Conditional operator) to select the redirect option.

This has only 1 statement if to allow the local storage key to be set. The default navigation removes the last else and the ternary removes the inner if else.

  ngOnInit(): void {
    this.activatedRoute.url.subscribe(() => {
      var navTo = "/error/404";
      const token = this.activatedRoute.snapshot.queryParamMap.get('token');
      if (token) {
        localStorage[AuthenticationStorageKey] = token;
        const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage');
        navTo = redirectPage ? redirectPage : "";
      }
      this.router.navigate(navTo);
    });
  }

As all paths through the code result in a redirect thus the last line uses navTo to redirect to the result of the branching.

This has the effect of reducing the cyclic complexity by 1 (depending on how you measure it)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.