Created
December 20, 2011 16:28
-
-
Save knaveofdiamonds/1502171 to your computer and use it in GitHub Desktop.
Self-schizophrenia example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.