Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
3 tasks done
JoshuaKGoldberg opened this issue Jan 20, 2024 · 4 comments
Labels
status: accepting prs Please, send a pull request to resolve this! type: feature New enhancement or request

Comments

@JoshuaKGoldberg
Copy link
Owner

Bug Report Checklist

  • I have tried restarting my IDE and the issue persists.
  • I have pulled the latest main branch of the repository.
  • 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 eslint/eslint#10120 but never ratified.

@johnnyreilly
Copy link
Sponsor Collaborator

I am quite interested in this

@lishaduck
Copy link

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

@johnnyreilly
Copy link
Sponsor Collaborator

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

@lishaduck
Copy link

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? 🙃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: accepting prs Please, send a pull request to resolve this! type: feature New enhancement or request
Projects
None yet
Development

No branches or pull requests

3 participants