Good vs. Bad

Which would you rather maintain?

good_code_bad_code

 

Advertisements

Functional creepin’ in?

Practicing the craft (programming).  Couldn’t stop messing with this one.
Kinda proud
– max 1 param on methods!
– 5 line max on methods !
– 50 line class
– readable code

But what’s what all the Proc’s and map operations (selects)?
Seems like I’m starting to get that functional feelin’!

class FerryBookings
  attr_accessor :current_side_of_river
  attr_accessor :number_of_ferry_trips
  attr_accessor :passengers

  def initialize
    @passengers = []
    @current_side_of_river = 'N'
    @number_of_ferry_trips = 0
  end

  def add_passenger(direction_headed)
    passenger = Passenger.new(direction_headed)
    @passengers << passenger
  end

  def ferry_person(person)
    person.moved = true
    switch_river_side
  end

  def ferry_all_passengers
    not_moved = Proc.new { |p| !p.moved? }
    while @passengers.select(&not_moved).size > 0
      passengers_left= @passengers.select(&not_moved)
      make_trip_south_and_north(passengers_left)
    end
  end

  def make_trip_south_and_north(passengers)
    ['S','N'].each do |direction|
      by_direction = Proc.new { |p| p.direction_headed == direction }
      ferry_trip(passengers.select(&by_direction))
    end
  end

  def ferry_trip(passengers)
    if passengers.count > 0
      ferry_person( passengers.first )
    elsif passengers_left_to_move?
      @number_of_ferry_trips += 1
    end
  end

  def passengers_left_to_move?
    @passengers.select{ |passenger| !passenger.moved? }.size > 0
  end

  def switch_river_side
    @current_side_of_river = (@current_side_of_river == 'N') ? 'S' : 'N'
    @number_of_ferry_trips += 1
  end

end