create-typescript-app icon indicating copy to clipboard operation
create-typescript-app copied to clipboard

🚀 Feature: Find or create a lint rule to prefer inverting a single 'if' to reduce nesting

Open JoshuaKGoldberg opened this issue 1 year ago • 4 comments

Bug Report Checklist

  • [X] I have tried restarting my IDE and the issue persists.
  • [X] I have pulled the latest main branch of the repository.
  • [X] I have searched for related issues and found none that matched my issue.

Overview

I often see functions like:

function doSomething() {
  if (someCondition) {
    const someOtherValue = getSomething();
    doSomethingWithSomeOtherValue();
  }
}

If a function consists entirely of an if and that if contains a declaration, I'd generally consider it cleaner to instead invert the if to reduce nesting:

function doSomething() {
  if (!someCondition) {
    return;
  }

  const someOtherValue = getSomething();
  doSomethingWithSomeOtherValue();
}

Let's find or create an ESLint plugin to do this.

Additional Info

https://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting goes into the reasoning for this nicely.

This was proposed to ESLint in https://github.com/eslint/eslint/issues/10120 but never ratified.

JoshuaKGoldberg avatar Jan 20 '24 03:01 JoshuaKGoldberg

I am quite interested in this

johnnyreilly avatar Feb 05 '24 17:02 johnnyreilly

@regru/eslint-plugin-prefer-early-return provides this rule (the ESLint config I use includes it, I've found it to be quite handy).

lishaduck avatar Aug 25 '24 20:08 lishaduck

I like to think that libraries would be keen on this rule (I'm so sorry)

johnnyreilly avatar Aug 25 '24 21:08 johnnyreilly

I like to think that libraries would be keen on this rule (I'm so sorry)

I don't understand. What are you trying to say? I interpret this as meaning that "libraries would find that rule more helpful, so it doesn't make sense for this template", but I doubt that's what you meant. Can you clarify? 🙃

lishaduck avatar Aug 25 '24 22:08 lishaduck