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 ifelse.

     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\$

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.