Skip to main content

No of Lines of Code in A Function

  • Lesser the lines of code, the easier it is to read and understand.
    • A nice descriptive name and 1 line of code, that's the best function we can write.
    • Why write 1 line of code into a separate function? Well, to give it a descriptive name and so that it can be reused if needed.
  • But of course not all functions can be 1 liners. But on the other hand, too big function becomes much harder to read. So we should have a limit: 10 lines max in a function

The authentication example from avoiding nested if checks is around 11 lines, it can still be broken down into smaller pieces as follows:

DO NOT split like this 💩💩💩
/**
* While it might be tempting to split it like this,
* It's actually hard to understand what's going on 💩
*/

function isTokenEmpty(token) {
// nothing to do if the auth header doesn't exist
if (!token) return 401;

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

const bearerToken = headerParts[1];
if (bearerToken === '') return 401; // empty token
}

function authenticate(req, res, next) {
// nothing to do if authModule isn't ready for some reason.
if (!authModule.initialized) throw new Error('Auth Module is not initialized');

// this function doesn't return anything, so we don't know what it does,
// We're forced to open and look into this function to understand what it does! 💩
isTokenEmpty(req.headers['Authentication']);

try {
const payload = authModule.validateToken(req.headers['Authentication'].split(' ')[1]);
return payload;
} catch (err) {
return 401;
}
}
Instead do like this ✅
function sanitizeToken(token) {
// nothing to do if the auth header doesn't exist
if (!token) return '';

const headerParts = token.split(' ');
if (headerParts.length !== 2) return ''; // header value is wrong

const bearerToken = headerParts[1];
if (bearerToken === '') return ''; // empty token

return bearerToken;
}

function authenticate(req, res, next) {
// nothing to do if authModule isn't ready for some reason.
if (!authModule.initialized) throw new Error('Auth Module is not initialized');

// We don't need to open the following function,
// unless we're really interested to see how it sanitizes the token ✅
const token = sanitizeToken(req.headers['Authentication']);
if (token === '') return 401;

try {
const payload = authModule.validateToken(token);
return payload;
} catch (err) {
return 401;
}
}