DEV Community

Cover image for Conditional Statements : Part 1
Rahul Raj
Rahul Raj

Posted on

Conditional Statements : Part 1

There are a lot of conditional statements in programming but how we can utilize them in a better way?

Consider the below code

  private demo(myVar: string): string {
    let myReturnVar: string;
    if(myVar === 'condition'){
      myReturnVar = 'It is condition';
    }else {
      myReturnVar = 'It is not condition';
    }
    return myReturnVar;
  }

  demo('condition'); // 'It is condition'
  demo(''); // 'It is not condition'
Enter fullscreen mode Exit fullscreen mode

With a cognitive complexity of 4 it fulfills our need but is it good?
As a developer we are expected to write clean code. And the above can be modified to be better.

Process of modification:

  • Why to use a variable myReturnVar when we can directly return the value as we are not going to utilize it except returning.
  • Once we return the data why we need a separate else statement to check. Let us see the below code:
  private demo(myVar: string): string {
    if(myVar === 'condition'){
      return 'It is condition';
    }
    return 'It is not condition';
  }
Enter fullscreen mode Exit fullscreen mode

The cognitive complexity remains the same (4) but now the code is cleaner then the previous.

But do we really need a if-else condition, we can do it using a ternary operator which reduces the complexity to (3)

  private demo(myVar: string): string {
    return myVar === 'condition' ? 'It is condition' : 'It is not condition';
  }
Enter fullscreen mode Exit fullscreen mode

By the above we can say that if there is a single line check it is better to use a ternary operator.

What about large conditions?

  private demo(myVar: string): string {
    if(myVar === 'condition') return 'C1';
    if(myVar === 'demo') return 'C2';
    if(myVar === 'thing') return 'C3';
    if(myVar === 'demo1') return 'C4';
    if(myVar === 'demo5') return 'C5';
    return '';
  }

  private demo1(myVar: string): string {
    switch (myVar) {
      case 'condition': return 'C1';
      case 'demo': return 'C2';
      case 'thing': return 'C3';
      case 'demo1': return 'C4';
      case 'demo5': return 'C5';
      default: return '';
    }
  }
Enter fullscreen mode Exit fullscreen mode

We can do it in both ways with cognitive complexity of (12) & (14) respectively.

There are always better ways to write the conditional statements.
We will continue going through those soon.

If you like the post follow me for more

Top comments (0)