« Back to Index

Avoid direct access to complex data structures, transform them to avoid problems when the structure changes

View original Gist on GitHub

1. Bad Example.rb

class MyClass
    attr_reader :data
    
    def initialize(data)
        @data = data
    end

    def do_something
        data.each do |item| 
            puts item[0]
            puts item[1]
            puts '---'
        end
    end
end

obj = MyClass.new([[10, 25],[3, 9],[41, 7]])
obj.do_something

2. Better Example.rb

class MyClass
    attr_reader :new_data
    
    def initialize(data)
        @new_data = transform(data)
    end

    def do_something
        new_data.each do |item| 
            # now we are able to reference easily understandable 
            # property names (rather than item[0], item[1])
            puts item.coord_x
            puts item.coord_y
            puts '---'
        end
    end

    Transform = Struct.new(:coord_x, :coord_y)
    
    def transform(data)
        data.map { |item| Transform.new(item[0], item[1]) }
    end
end

obj = MyClass.new([[10, 25],[3, 9],[41, 7]])
obj.do_something