Class: Reek::Smells::ControlParameter

Inherits:
SmellDetector show all
Defined in:
lib/reek/smells/control_parameter.rb

Overview

Control Coupling occurs when a method or block checks the value of a parameter in order to decide which execution path to take. The offending parameter is often called a Control Couple.

A simple example would be the quoted parameter in the following method:

def write(quoted)
  if quoted
    write_quoted(@value)
  else
    puts @value
  end
end

Control Coupling is a kind of duplication, because the calling method already knows which path should be taken.

Control Coupling reduces the code's flexibility by creating a dependency between the caller and callee: any change to the possible values of the controlling parameter must be reflected on both sides of the call.

A Control Couple also reveals a loss of simplicity: the called method probably has more than one responsibility, because it includes at least two different code paths.

One possible solution is to use the Strategy Pattern to pass into the callee what must be done. This is not considered to be control coupling because the callee will do the same thing with the strategy, whatever it happens to be. Sometimes in Ruby the strategy may actually just be a block passed in, and that remains next to where the caller invokes it in the source code.

Defined Under Namespace

Classes: ControlParameterCollector, ControlParameterFinder, FoundControlParameter

Constant Summary

Constants inherited from SmellDetector

SmellDetector::DEFAULT_EXCLUDE_SET, SmellDetector::EXCLUDE_KEY

Instance Attribute Summary

Attributes inherited from SmellDetector

#smell_category, #smell_type, #smells_found, #source

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from SmellDetector

#config_for, #configure_with, contexts, default_config, default_smell_category, #enabled?, #enabled_for?, #examine, #exception?, #initialize, #register, #report_on, smell_type, #value

Constructor Details

This class inherits a constructor from Reek::Smells::SmellDetector

Class Method Details

.smell_categoryObject


44
45
46
# File 'lib/reek/smells/control_parameter.rb', line 44

def self.smell_category
  'ControlCouple'
end

Instance Method Details

#examine_context(ctx) ⇒ Array<SmellWarning>

Checks whether the given method chooses its execution path by testing the value of one of its parameters.

Returns:


54
55
56
57
58
59
60
61
62
# File 'lib/reek/smells/control_parameter.rb', line 54

def examine_context(ctx)
  ControlParameterCollector.new(ctx).control_parameters.map do |control_parameter|
    SmellWarning.new self,
                     context: ctx.full_name,
                     lines: control_parameter.lines,
                     message: "is controlled by argument #{control_parameter.name}",
                     parameters: { name: control_parameter.name.to_s }
  end
end