The Law of Demeter or Principle of Least Knowledge is a design guideline for developing software. The fundamental notion is that a given object should assume as little as possible about the structure, properties and behavior of anything else (including its subcomponents).
Dan Manges helped to clarify the concept and the way to apply it in Ruby, notably through the use of the
Forwardable module. Using mocks and stubs, Luke Redpath came across Demeter's law violation when writing his Unit Tests:
class WidgetsControllerCreateActionTest < Test::Unit::TestCase
def setup
@user = mock('user')
User.stubs(:find).returns(@user)
end
def test_should_create_new_widget_for_parent_user_using_posted_widget_params
widgets_proxy = mock('association proxy')
@user.stubs(:widgets).returns(widgets_proxy)
# Demeter's Law Violation here by using the widget_proxy through User object
widgets_proxy.expects(:create).with(:name => 'my funky widget')
post :create, :widget => {:name
=> 'my funky widget'}
end
The solution is to add a delegate method on all your models. But that quickly becomes boring, which is the reason why Luke introduced the
Demeter's Revenge plugin which will create a collection of Demeter-compliant methods for your
has_many
and
has_and_belongs_to_many
associations:
user.build_widget(params)
user.create_widget(params)
# ...
But aren't laws made to be broken? And the fact that a plugin can
automate a so called "Law" isn't this making it null and void?