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

[new cop] Require parentheses #714

Closed
cbarraford opened this issue Jan 3, 2014 · 4 comments
Closed

[new cop] Require parentheses #714

cbarraford opened this issue Jan 3, 2014 · 4 comments
Assignees

Comments

@cbarraford
Copy link

Rubocop, prefers the use of && over and. This isn't just a syntactic change, it also changes how if statements are evaluated. In the example below, notice in way one, the include? statement has a space then tuesday. While, way two uses parentheses instead of a space.

#!/usr/bin/env ruby
# ruby 2.0

weekdays = %w[
  sunday
  monday
  tuesday
  wednesday
  thursday
  friday
  saturday
]

# way 1
puts 'way one'
if weekdays.include? 'tuesday' && true == true
  puts 'its true'
else
  puts 'its false'
end

puts
# way 2
puts 'way two'
if weekdays.include?('tuesday') && true == true
  puts 'its true'
else
  puts 'its false'
end

Output

way one
its false

way two
its true

As you can see, the outcome of the if statement is different, and its not immediately obvious why. Furthermore this failure, fails silently which is even worse.

I propose a new cop that enforces the use of parentheses for cases such as this. Thoughts?

@jonas054
Copy link
Collaborator

jonas054 commented Jan 3, 2014

I think that's an excellent idea. There's a rule in the Style Guide that says

Omit parentheses around parameters for methods that are part of an internal DSL (e.g. Rake, Rails, RSpec), methods that have "keyword" status in Ruby (e.g. attr_reader, puts) and attribute access methods. Use parentheses around the arguments of all other method invocations.

And I think we've stayed away from a cop implementation of it because it's so difficult to know what's a DSL and what isn't. But the more limited case of semantically problematic omission of parentheses might be easier to implement a cop for, a lint cop.

@bbatsov
Copy link
Collaborator

bbatsov commented Jan 3, 2014

Yeah, that sounds reasonable. I guess we can also have some cop checking for parens used in built-in Ruby DSL methods (like attr_, puts, p, etc), as we obviously know them.

@mattwhite
Copy link

Or just enforce parantheses when the line contains one of: and, or, not, &&, ||, !

The order of operations can be tricky to remember, especially if you also use python.

@claco
Copy link
Contributor

claco commented Jan 21, 2014

👍 on this one. I would love to have this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants