This one is easy to implement and use in almost any object oriented code, but we see violations of this principle everywhere.

In simple words it means use just one dot (.), but the complete definition it that a method can call other method of its own class and methods on the classes of its own instance variables.

One example will clarify this concept:

1
2
3
4
5
6
7
8
9
class Drummer < ActiveRecord::Base
  has_one :drumset
end

class DrumSet < ActiveRecord::Base
  bellongs_to :drummer
end

 @drummer.drumset.play # => Demeter violation

To solve this violation we have to define (delegate) the play method on the Drummer class, like so:

1
2
3
4
5
6
7
8
9
10
11
12
class Drummer < ActiveRecord::Base
  has_one :drumset
  def play; drumset.play ; end
  # more elegant solution

  delegate :play, to: :drumset
end

class DrumSet < ActiveRecord::Base
  bellongs_to :drummer
end

 @drummer.play # => no Demeter violation

This is just a simple example, but in reality they are more nested (Customer with wallet, and balance for example), but the solutions is just as simple. Use delegation and don’t talk to strangers