DEV Community

Naomi Dennis
Naomi Dennis

Posted on

2

Favorite Refactoring Techniques: Extract Functions

The next refactoring technique we'll look at is extracting behavior into functions. Say we have the following example:

class SubwayTrain
attr_accessor :averageSpeed, :subwayCar, :speed, :subwayCars
def initialize
self.averageSpeed = 17
self.speed = 0;
self.subwayCars = [];
end
def allowPassengersOnBoard
puts "Train arriving at station."
while(speed > 0)
self.speed -= 1
end
puts "Train Stopped."
puts "Doors Open."
subwayCars.each do | subwayCar |
subwayCar.open()
end
sleep 1
subwayCars.each do | subwayCar |
subwayCar.close()
end
puts "Stand Clear of the Closing Doors"
while(speed < averageSpeed)
self.speed += 1
end
puts "Train leaving station."
end
end
train = SubwayTrain.new
train.speed = 100;
train.allowPassengersOnBoard()

SubwayTrain#processStop has a lot of behavior. The intention could be made clearer by separating each behavior into its own method. The behavior we extract will also become available to other classes that may need it, outside of the context of getting passengers at a subway station.

After extracting the behavior, #processStop looks like this:

class SubwayTrain
attr_accessor :averageSpeed, :subwayCar, :speed, :subwayCars
def initialize
self.averageSpeed = 17
self.speed = 0;
self.subwayCars = [];
end
def allowPassengersOnBoard
puts "Train arriving at station."
slowDownToHalt
puts "Train Stopped."
openDoors
puts "Doors Open."
sleep 1
puts "Stand Clear of the Closing Doors"
increaseSpeedToAverageSpeed
puts "Train leaving station."
end
def slowDownToHalt
while(speed > 0)
self.speed -= 1
end
end
def openDoors
subwayCars.each do | subwayCar |
subwayCar.close()
end
end
def increaseSpeedToAverageSpeed
while(speed < averageSpeed)
self.speed += 1
end
end
end
train = SubwayTrain.new
train.speed = 100;
train.allowPassengersOnBoard

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay