Subsecciones

4: refactor

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.

Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

Martin Fowler


"We don't have time for refactoring, there's still too much left to do"

[~/local/src/ruby/LPP/rspec_examples/rpcalculator(master)]$ cat  spec/math/rpcalc_spec.rb
#require File.join(File.dirname(__FILE__), "/../spec_helper")
require "spec_helper"
module Math
  describe RPCalc do
    before :each do
      @c = Math::RPCalc.new
    end

    context "When an erroneous input is given" do
      before :each do
        @e = proc { @c.calc('a') }
      end
      it "must raise an exception" do
        expect { @e[] }.to raise_error(SyntaxError)
        expect { @e[] }.to raise_error("Error. found 'a'. Expected number or operator")
      end
    end
  end
end

[~/local/src/ruby/LPP/rspec_examples/rpcalculator(master)]$ rake spec
rspec -Ilib -Ispec spec/math/rpcalc_spec.rb

Math::RPCalc
  When an erroneous input is given
    must raise an exception

Finished in 0.00184 seconds
1 example, 0 failures
[~/local/src/ruby/LPP/rspec_examples/rpcalculator(master)]$

Las Cuatro Reglas de Kent Beck para un Diseño Simple

Use Kent Beck's four rules of simple design to guide you:

  1. Run all the tests
  2. Contain no duplicate code
  3. Express all the ideas the author wants to express
  4. Minimize classes and methods

By re-running the test cases, the developer can be confident that code refactoring is not damaging any existing functionality.

Casiano Rodriguez León 2015-01-07