Skip to main content

Avoid Nested if Checks

Hard to read - Auth token validation logic 💩🧨💣
if (authModule.initialized) {
const authHeader = req.headers['Authentication'];
if (authHeader) {
const headerParts = authHeader.split(' ');
if (headerParts.length === 2) {
const token = headerParts[1];
if (token !== '') {
try {
const payload = authModule.validateToken(token);
return payload;
} catch (err) {
return 401;
}
}
return 401;
}
return 401;
}
return 401;
}
return 401;
Easy to read - Auth token validation logic ✅
// nothing to do if authModule isn't ready for some reason.
if (!authModule.initialized) throw new Error('Auth Module is not initialized');

const authHeader = req.headers['Authentication'];
if (!authHeader) return 401; // Auth header doesn't exist

const headerParts = authHeader.split(' ');
if (headerParts.length !== 2) return 401; // Header value is wrong

const token = headerParts[1];
if (token === '') return 401; // Empty token

// now we know token exists
try {
const payload = authModule.validateToken(token);
return payload;
} catch (err) {
return 401;
}
  • Nested if conditions are harder to read, as the reader has to move up and down to see what happens in else, which if case is wrapped under which and so on.
  • Most of the time we perform if checks to validate some data before proceeding. E.g. to validate auth token, we have to make sure auth validator is initialized and ready, the authentication header exists, header value is in the correct format and the token does exists, before we can perform the validation of the token.
  • We should always check if the required data exists or is valid before proceeding.
tip

Roll out the error conditions first, step by step.