New rule request: naming conventions of methods
See original GitHub issueI looked for a rule for enforcing naming conventions on methods of a class but I couldn’t find any.
As an example, the AirBnb style guide for React forbids prefixing methods with an underscore, but there is no way in ESLint to enforce it.
The rule I’m proposing would be an equivalent of no-underscore-dangle
but for methods.
Valid examples
class Foo {
bar() { }
}
Invalid examples
class Foo {
_bar() { }
}
The rule has two purposes: enforcing a common style and preventing errors. The rationale behind the error prevention is that prefixing with an underscore may give a false sense of privacy, which in turn can cause mistakes, e.g. breaking changes to a method which was thought to be private.
I have already a working implementation of a more generic version of this rule https://github.com/buildo/eslint-plugin-method-names, which allows specifying a regex to which method names should confirm.
I think at least the underscore-specific version should be in the core rules, to match the no-underscore-dangle
rule.
Open questions (if the proposed rule is valid):
-
should the rule scope be limited at the underscore case or should it be generic and allow a regex to be specified?
-
should the rule scope include class properties defining a function? (my plugin currently does). E.g.
class Foo { bar() { } // method, invalid _baz = () => {} // class property, method }
would be both invalid. This is a fairly common use case when using React components, in order to bind handlers.
-
Updated proposal, after the discussion below
no-underscore-dangle
will have one additional option:
enforceInMethodNames
(default:false
)
enforceInMethodNames
Examples of correct code for this rule with the { "enforceInMethodNames": true }
option:
class Foo {
foo() {}
}
const o = {
foo() {}
}
Examples of incorrect code for this rule with the { "enforceInMethodNames": true }
option:
class Foo {
_foo() {}
}
class Foo {
foo_() {}
}
const o = {
_foo() {}
}
const o = {
foo_() {}
}
The rationale between the additional option and its default value is to make this change non-breaking.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:5
- Comments:42 (42 by maintainers)
Top GitHub Comments
It’s unfortunate to have options where absence is not the same as
false
😕 could we invert the option names so that the defaults can befalse
?Okay, we’ve gone off track. That’s my fault, I apologize, but let’s please get back on track.
If we can get a full proposal for extending no-underscore-dangle to optionally support method names and class properties, then the team can evaluate.
Sound good? 😄