reverse-refactor



reverse-refactor

0 0


reverse-refactor

Guided Exploration on Writing Your Dream Code

On Github cupakromer / reverse-refactor

Project Euler

Each new term in the Fibonacci sequence is generated by adding the previous two terms.

By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

https://projecteuler.net/problem=2

Dream Code

Reverse Refactoring

Aaron Kromer @cupakromer

Disclaimer

http://i.imgur.com/5zUjSec.jpg

Scrappy Academy

https://github.com/ScrappyAcademy/welcome

Review: Project Euler

Each new term in the Fibonacci sequence is generated by adding the previous two terms.

By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

https://projecteuler.net/problem=2

Solution?

limit = 4_000_000
sum = 0
a, b = 1, 1
loop do
  sum += b if b.even?
  a, b = b, a + b
  break if b > limit
end

puts sum

Dream Code (mine)

Fibonacci.upto(4_000_000).evens.sum
Fibonacci.upto(4_000_000).select(&:even?).sum

Implementation

Fibonacci.upto(4_000_000).evens.sum
Fibonacci = Enumerator.new{ |y|
  a = b = 1
  loop do
    y << a
    a, b = b, a + b
  end
}

Implementation

Fibonacci.upto(4_000_000).evens.sum
module Enumerable
  def evens
    select{ |num| num.even? }
  end

  def upto(limit)
    return enum_for(__callee__, limit) unless block_given?
    each do |num|
      break if num > limit
      yield num
    end
  end

  def sum
    reduce(0){ |sum, num| sum += num }
  end
end

Refactoring 👍

💚 💙 💜 💛

Refactor: Defined

"a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior"

Fowler, Martin. Refactoring: Improving thr Design of Existing Code. Boston, MA: Addison-Wesley, 2000. pg. 53

Common Refactor Methods

Refactor Name Reverse Method Extract Class Create Object Extract Interface Create Object Extract Method Create Message Extract Parameter Create Object Extract Subclass Create Object Move Method API/Contract Design Pull Up Method API/Contract Design Push Down Method API/Contract Design Replace Conditional /w Polymorphism Create Objects/Command

Think Critically

http://fc06.deviantart.net/fs70/i/2012/286/a/8/turn_your_brain_on_by_simon93_ita-d5ho4og.png

Examples

Dream Code

Aaron Kromer

Created with: reveal.js by Hakim El Hattab