Skip to content

Instantly share code, notes, and snippets.

@knaveofdiamonds
Created December 20, 2011 16:28
Show Gist options
  • Save knaveofdiamonds/1502171 to your computer and use it in GitHub Desktop.
Save knaveofdiamonds/1502171 to your computer and use it in GitHub Desktop.
Self-schizophrenia example
# Self-schizophrenia example
class A
def foo
"foo"
end
def bar
"bar"
end
# Crucially, the invariant should be that this method returns
# whatever foo returns, plus whatever bar returns
def foobar
foo + bar
end
end
# Now with delegation:
require 'delegate'
class B < DelegateClass(A)
def foo
"baz"
end
end
b = B.new(A.new)
b.foo # => "baz", all is fine
b.bar # => "bar", all is fine
b.foobar # => "foobar", arrrgh, inconsistency: should be "bazbar"
# But with mixins, DCI-style:
module C
def foo
"baz"
end
end
a = A.new
a.extend C
a.foo # => "baz", all is fine
a.bar # => "bar", all is fine
a.foobar # => "bazbar", all is fine
@gregory
Copy link

gregory commented Jan 5, 2014

I think you are doing it wrong in a DCI context.
In DCI, you'll want to decorate your object to add behaviours, not to overwrite them, so having a foo method in A class doesn't makes sens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment