Monday, September 26, 2016

Implemenation Aware Client and Data Agnostic Implementation

Implementation Aware Client 

class Grass
  attr_reader :color

  def initialize
    @color = 'green'
  end
end

grass = Grass.new

if grass.color == 'green'
  p 'do something for the green object'
end

This example gets the data from the object and uses it in some fashion to make a decision in the conditional.

Data Agnostic Implementation 

class Grass
  def green?
    true
  end
end

grass = Grass.new
if grass.green?
  p 'do something for the green object'
end 

This example, does not get the data from the object, instead, it requests for some service to be provided by the object. The object provides the service by working with the data internal to the class. The data is hidden from the clients.

Why is this better than the first example? This approach is insensitive to data structure changes. So if you decide you need to use Struct instead of a string to represent the concept of green, your clients will not break.

No comments:

Post a Comment