visit
Using if
statement is a clunky way of writing code and should be avoided wherever possible (in most situations, this is almost 100% of the time).
Don’t get me wrong, if
statements are useful in certain scenarios and are there for a reason. However, overusing them in areas where they can be avoided will not only make your life harder when it comes the time to revisit the code in a few months' time, but also impact the time it takes for a dev to understand the context of the code and continue with the task that has been assigned to them. This disrupts the “flow” and contributes to lower overall efficiency. Less is more.
async validateCard(encryptedCardNumber) {
const card = await this.lookupCard(encryptedCardNumber);
if (!card) {
console.log(NotFoundResponse.message);
return NotFoundResponse;
}
else if (card.isBlacklisted) {
console.log(BlacklistedReponse.message);
return BlacklistedResponse;
}
else if (card.isDeleted) {
console.log(DeletedResponse.message);
return DeletedResponse;
}
else if (card.status !== CardStatus.active) {
console.log(InactiveResponse.message);
return InactiveResponse;
}
else {
console.log(ValidResponse.message);
return ValidResponse;
}
}
Having these many if
statements not only require quite a bit of effort to decipher, but as more conditions get added, we’ll soon be scrolling up and down to ensure each and every case has been met, adding more fuel to the fire. Alongside this, there also seems to be code duplication which can be extracted for the sake of maintainability.
&&
) evaluates operands from left to right, returning immediately with the value of the first operand it encounters; if all values are , the value of the last operand is returned.||
) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. With short-circuit evaluation, it simply returns the first truthy expression.
async validateCard(encryptedCardNumber) {
const card = await this.lookupCard(encryptedCardNumber);
const response =
!card && NotFoundResponse ||
card.isDeleted && DeletedResponse ||
card.isBlacklisted && BlacklistedResponse ||
card.status !== cardStatus.active && InvalidStatus ||
ValidResponse;
console.log(response.message);
return response;
}
Create a function that converts a given number between 1–10 into words
function convertIntegerToText(num) {
if (num === 1) return "one";
if (num === 2) return "two";
if (num === 3) return "three";
// ...
if (num === 10) return "ten";
}
The requirements have changed. We now want to use this function to convert numbers between 1–100 into words
A scalable solution is therefore a code where there is either no if
statements whatsoever or a few statements that can cover the majority of the cases, if not all, with minimal to no modifications required.
const ONES = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
const TEENS = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
const TENS = ["", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"];
function convertIntegerToText(num) {
if (num < 20)
return ONES[num] ?? TEENS[num - 10];
if (num < 100)
return `${TENS[Math.floor(num / 10)]} ${convertIntegerToText(num % 10)}`;
if (num < 1000)
return `${ONES[Math.floor(num / 100)]} hundred ${convertIntegerToText(num % 100)}`;
throw new Error("Number too high");
}
// home.jsx
function getCompanyTemplate(company) {
if (company === "apple") {
return <AppleTemplate />
}
if (company === "samsung") {
return <SamsungTemplate />
}
if (company === "sony") {
return <Sony />
}
if (company === "lg") {
return <Lg />
}
}
// OR
// index.jsx
export const templates = {
apple: <Apple />,
samsung: <Samsung />,
sony: <Sony />,
lg: <Lg />,
}
// home.jsx
import { templates } from "./index"
function getCompanyTemplate(company) {
return templates[company];
}
My previous showcases an in-depth scalable frontend solution without any if
statements. Be sure to check it out!