Reputation: 2662
I'm using reek
as an analyzing tool for best practices in my code. However recently I found that if in the method, I have boolean parameters, such as.
def method (flag = true)
reek
gives me a warning. Why does reek
tell me that it is a warning?
Upvotes: 8
Views: 7290
Reputation: 448
A couple of years before I wrote reek I blogged about this code smell here:
http://silkandspinach.net/2004/07/15/avoid-boolean-parameters/
The problems with Boolean parameters all have to do with duplication and the SRP: the called method has two responsibilities, and the caller knows which one it wants to invoke.
Upvotes: 6
Reputation: 69
To create default Boolean parameters in Ruby that passes Linters check like RuboCop use:
def method (flag: true)
end
then call like this:
method (flag: true)
method (flag: false)
the most important thing to note is that any method definition that has optional parameters must be called with the names of all the optional arguments specified.
Upvotes: 0
Reputation: 2889
Old question, but I thought I'd add my thoughts for people who come in from google:
Separate methods are fine in some cases, but the better option generally in my mind is following:
def method(option = {:flag => false})
options[:flag] ? doFoo : doBar
end
method(:flag => true)
This also could include a check if the flag is actually a boolean:
def method(option = {:flag => false})
flag = options.fetch(:flag) { false }
unless [true, false].include?(flag)
raise ArgumentError, ':flag option should be true or false'
end
flag? doFoo : doBar
end
method(:flag => true)
Upvotes: 2
Reputation: 13097
A flag variable is considered bad practice. This is because it inherently violates the principle that functions should do one, and only one, thing. By passing in a boolean flag you are saying, "Do this if it's true, and that if it's false", which is two things.
Upvotes: 0