DEV Community

Mohammad Jamal Dashtaki
Mohammad Jamal Dashtaki

Posted on

Smart use of “if/else”

Actually, this article is not against the if/else but tries to show how following an anti-if pattern will improve your code quality. First thing first, I think we have to know how to use if/else could be improved your code quality in terms of reading(readability) and hard to debug(maintainability)
There are pretty many articles on the internet that lead you to prevent using if/else and being an Anti-If developer.

In some cases using shorthand if/else might also be helpful because it avoids branching your code which costs more in terms of complexity.
For instance in this case you can get rid of else just by return there is no code branching too:

No code branching

Ternary Operator (?:)

If you want to shorten If/else and in this case else part is mandatory, you can use ?: operator as:

condition ? action-on-true : action-on-false(else)
// For instance
const gender = isMale ? 'Male' : 'Female';
Enter fullscreen mode Exit fullscreen mode

I see this kinda short hand format used for null/undefined checking like:

const avatarName = user.firstname ? user.firstname : user.lastname;
Enter fullscreen mode Exit fullscreen mode

However in this case you can simply use:

const avatarName = user.firstname ?? user.lastname
// or depends on your case you can use  "||"
const avatarName = user.firstname || user.lastname
Enter fullscreen mode Exit fullscreen mode

Logical Operator (&&)

In another case, if you have only if condition you can use && operator as:

condition && action;
// For instance
!this.settings && (this.settings = new TableSettings());
Enter fullscreen mode Exit fullscreen mode

You can also use polymorphism to avoid using if/else like as an example below which is really more readable/maintainable, Here is the code :
no polymorphism

And then it can be implemented by polymorphism:
polymorphism

Conslusion:

I hope it did help but anyway in order to write a code that is reliable we have to apply best practices.

Top comments (0)