Description
I 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.