Skip to content

Commit

Permalink
* Refactor.
Browse files Browse the repository at this point in the history
Use a specific exception instead of ArgumentError, thus saving us from:
* Rescuing errors we didn't mean to rescue
OR
* Having an ugly being-rescue block at the start of #place.
  • Loading branch information
ledestin committed Apr 6, 2014
1 parent eb5ba21 commit 8db8253
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion robot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def place x, y, direction
return unless @@table.contain? new_coords.x, new_coords.y

@coords = new_coords
rescue ArgumentError
rescue StateArgumentError
end

def report
Expand Down
5 changes: 5 additions & 0 deletions spec/state_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,9 @@
state = Robot::State.new 0, 0, 'NORTH'
expect(state.to_s).to eq '0,0,NORTH'
end

it 'raises State if a constructor argument is invalid' do
expect { Robot::State.new 'a', 0, 'NORTH' }.to \
raise_error Robot::StateArgumentError
end
end
4 changes: 4 additions & 0 deletions state.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
require './direction'

class Robot
class StateArgumentError < ArgumentError; end

State = Struct.new(:x, :y, :direction) do
def initialize x, y, direction
self.x, self.y, self.direction =
Integer(x), Integer(y), Direction(direction)
rescue ArgumentError
raise StateArgumentError, $!.message
end

def to_s
Expand Down

0 comments on commit 8db8253

Please sign in to comment.