ESLint Setting to Avoid Spaghetti Code! - Complexity

Are you struggling with a spaghetti codebase?

Are you looking for ways to write cleaner code or improve the readability of your team's codebase?

One ESLint rule that I usually add to my teams codebases is the complexity setting.

What does that do?

Enforce a maximum cyclomatic complexity allowed in a program

Okay what does that do but in English?

It limits the if/else paths that can be nested in a single group.

I think looking at an example in action will make this more understandable:

/*eslint complexity: ["error", 2]*/

function isBiggerThanTen(x) {
    if (x <= 10) {
        return "Not bigger than 10"; // 1st path
    } else if (x > 10) {
        return "Bigger than 10"; // 2nd path
    } else {
        // Will error because of the 3rd path and we have set complexity error to `2`
        return "I don't understand the input"; // 3rd path

Our code will error in this example because we have limited the complexity to 2.

So how do you get around writing complex code with such limitations?

You start breaking your code into smaller functions, making it easier to test and understand, which will undoubtedly produce fewer bugs. 🐞

It always frustrates teams when they first start (mainly when they are used to writing deeply nested if/else code), but it usually melts away after a few weeks into a new appreciation for simplified code.

You'll also notice how code with limited complexity is much easier to review and usually results in faster delivery cycles too!

## How I use it

This example in my opinion, might be a little low of a setting, and I usually aim for a setting of ["error", 4].

Common frustration I've found

I often notice people throwing it out after they hit their first switch statement. The workaround for these things is having key/value maps for outputs instead of the usual list of statements.

You can read the docs here to learn more.

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

EslintJavaScriptClean Code
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.