3

These two PHP class methods violates Single Responsibility Principle (SRP) according to the phpmd rule booleanargumentflag.

How should they be written to avoid this?

If the solution is to remove the default value "= true", then how is this improving the code?

/**
 * Set verbose mode.
 *
 * @param boolean $mode true or false to enable and disable verbose mode,
 *                      default is true.
 *
 * @return $this
 */
public function setVerbose($mode = true)
{
    $this->verbose = $mode;
    return $this;
}


/**
 * Use cache or not.
 *
 * @param string $use true or false to use cache.
 *
 * @return $this
 */
public function useCache($use = true)
{
    $this->useCache = $use;
    return $this;
}
Mikael Roos
  • 285
  • 3
  • 15
  • 1
    I'd assume this is that you use $this->verbose and $this->useCache in non-boolean contexts somewhere else, though I've not seen the error before myself. Also unrelated, $use has a @param string PHPDoc. – markdwhite Sep 16 '15 at 08:14

2 Answers2

3

The intention of this hint is to reduce the method's responsibilities. In this particular case, if the function of the method is to set some kind of behavior, it shouldn't have any default value. The default values belong to the class definition or its constructor.

You can just remove the parameter's default values and set them when you define the class properties. I.E.:

public $useCache = true;
2

Your example has two methods, each with two responsibilities: turning the thing on, and turning it off. Better to split each method to give each one responsibility only. Example:

public function setVerbose($flag);

becomes

public function setVerboseOn();
public function setVerboseOff();
Steve Almond
  • 413
  • 4
  • 12