class RuboCop::Cop::Metrics::Utils::AbcSizeCalculator

> ABC is .. a software size metric .. computed by counting the number > of assignments, branches and conditions for a section of code. > c2.com/cgi/wiki?AbcMetric

We separate the calculator from the cop so that the calculation, the formula itself, is easier to test.

Constants

BRANCH_NODES

> Branch – an explicit forward program branch out of scope – a > function call, class method call .. > c2.com/cgi/wiki?AbcMetric

CONDITION_NODES

> Condition – a logical/Boolean test, == != <= >= < > else case > default try catch ? and unary conditionals. > c2.com/cgi/wiki?AbcMetric

Public Class Methods

calculate(node) click to toggle source
# File lib/rubocop/cop/metrics/utils/abc_size_calculator.rb, line 24
def self.calculate(node)
  new(node).calculate
end
new(node) click to toggle source
# File lib/rubocop/cop/metrics/utils/abc_size_calculator.rb, line 28
def initialize(node)
  @assignment = 0
  @branch = 0
  @condition = 0
  @node = node
end

Public Instance Methods

calculate() click to toggle source
# File lib/rubocop/cop/metrics/utils/abc_size_calculator.rb, line 35
def calculate
  @node.each_node do |child|
    if child.assignment?
      @assignment += 1
    elsif BRANCH_NODES.include?(child.type)
      evaluate_branch_nodes(child)
    elsif CONDITION_NODES.include?(child.type)
      @condition += 1 if node_has_else_branch?(child)
      @condition += 1
    end
  end

  Math.sqrt(@assignment**2 + @branch**2 + @condition**2).round(2)
end
evaluate_branch_nodes(node) click to toggle source
# File lib/rubocop/cop/metrics/utils/abc_size_calculator.rb, line 50
def evaluate_branch_nodes(node)
  if node.comparison_method?
    @condition += 1
  else
    @branch += 1
  end
end
node_has_else_branch?(node) click to toggle source
# File lib/rubocop/cop/metrics/utils/abc_size_calculator.rb, line 58
def node_has_else_branch?(node)
  %i[case if].include?(node.type) &&
    node.else? &&
    node.loc.else.is?('else')
end