Don't mistake the global variables with attributes of object in OOD
Fri 17 Aug 2018

I have to say that we tend to make the attributes of class become messy. Attributes are the characters to distinguish class from the others. These ones make them different. It’s like black people who have black skin and vice versa. Moreover, if two black families which have the same black skin. But they have different skins. They are not the same.

class Route
   attr_reader :route, :starting_point, :ending_point

   def initialize(route)
      @route = route
      @starting_point = route.first
      @ending_point = route.last
   end
end

:starting_point and :ending_point are redundant. Because we can get them from route. Design like this is not efficient. 

We can choose between keeping route or :starting_point and :ending_point. 

Solution#1

class Route
   attr_reader :route

   def initialize(route)
      @route = route
   end

   private 
   def starting_point
      route.split("").first
   end

   def ending_point
      route.split("").last
   end
end

Normally, we shouldn't just keep the params remaining like this. We need to do something in order to initialize the results. 

That is not good:

  • initialize method doesn't really initialize anything.
  • it has to do "split" to get the point every time private methods involved (bad performance)

 Solution#2

class Route
   attr_reader :starting_point, :ending_point, :middle_stops

   def initialize(route)
      @middle_stops = route[1..route.length - 2].split('')
      @starting_point = @middle_stops.first
      @ending_point = @middle_stops.last
   end
end
  • each attribute can't derive the value from the others. Each one is separate and clear. 
  • initialize method does its responsibility to get ready for involving the public methods.