Boolean parameters in methods. Why not?

7k Views Asked by At

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?

4

There are 4 best solutions below

3
On BEST ANSWER

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.

0
On

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)
0
On

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.

3
On

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.