In ruby (and in CoffeeScript) you can say:
Is this merely a matter of preference, or could one be better than the other?
Let me make the case that
method(arg)is better… and that
method argis better. It all depends.
Let’s first make a distinction: expressions vs statements.
In ruby, all method invocations are expressions. That is, they have a value— same in CoffeeScript. Other languages have things similar to function invocations (often called subroutines) that are not expressions, but statements, having no value.
However, just because every method invocation in ruby (or coffeescript) is an expression doesn’t mean that we actually treat it as such. Sometimes, we treat a method invocation as a statement and ignore its value, usually because its value is completely uninteresting. For example:
Yes, it’s a method invocation. Does it have a value? Certainly. What is it? I have no idea. Nobody cares. Do we write ‘
has_many(:posts)'? No, that gets you labeled a rails noob. So, why parens sometimes and not other times?
Answer: Parentheses should indicate that you are treating the method invocation as an expression, even if you aren’t assigning its value.
- Because code is like math, and in math, f(x) means function application, and
- Because the parentheses are required for method chaining, which only makes sense when the method invocation is being treated as an expression.
So, parentheses actually subtly signal something semantic about your code. They say: “Hey, I’ve got a value. You might want to use it.” Likewise, a lack of parentheses says something, too: “Sorry, I’ve got no value for you to use - I’m all about my side-effects.”
So, go ahead: promote your parentheses (and lack thereof) from optional syntax to expressive code.
- Chris Shoemaker