Search code examples
rubyrubocopruby-style-guide

Why does the Rubocop default guidelines recommend parentheses in method definitions?


Why does Rubocop / the community-driven Ruby style guide recommend parentheses in method definitions?

def my_method(param1, param2)
end
# instead of
def my_method param1, param2
end

Method calls are allowed with or without parentheses depending on the situation. However, my first impression is that lack of parentheses in method calls are much more potentially ambiguous than lack of parentheses in method definitions. Was there a reason behind it, e.g. to make code more fool-proof, or did it happen because of "historical reasons" or "because it was the most widespread style"?

Clarification:

I am not asking for opinions about which style is easier to read.

The lint Lint/AmbiguousOperator is based on the idea that do_something *some_array is ambiguous and a source for bugs (Link). I wondered if this is the same case for Style/MethodDefParentheses (Link).

After going back to find the actual names of those Cops, my best guess right now is that there is no "technical" reason, but rather one is a proper "lint" and the other a "style" matter.


Solution

  • The rationale is omitted in the initial commit, of which this rule was part, indicating that there was no particular technical reason for it.

    The fact that the corresponding cop is placed in the Style department, rather than Lint, serves as further proof that this is a matter of just that, style.

    Method definitions have a very simple syntax. The def keyword is (optionally) followed by arguments, which must be followed by a terminator (newline or ;).

    The possible variations are:

    • single line method definitions,
    • inline modifiers, e.g. private,
    • default- and keyword arguments,
    • splat- and block arguments.

    All of these work fine both with and without parentheses. Furthermore, running a file with an unparenthesized method definition using the -w flag raises no warnings.

    These factors together rule out the possibility that the parentheses are recommended to avoid ambiguity.