Wrappers/law of demeter seems to be an anti-pattern...

Posted by Robert Fraser on Stack Overflow See other posts from Stack Overflow or by Robert Fraser
Published on 2010-03-31T06:47:01Z Indexed on 2010/03/31 6:53 UTC
Read the original article Hit count: 443

I've been reading up on this "Law of Demeter" thing, and it (and pure "wrapper" classes in general) seem to generally be anti patterns. Consider an implementation class:

class Foo {
    void doSomething() { /* whatever */ }
}

Now consider two different implementations of another class:

class Bar1 {
    private static Foo _foo = new Foo();
    public static Foo getFoo() { return _foo; }
}

class Bar2 {
    private static Foo _foo = new Foo();
    public static void doSomething() { _foo.doSomething(); }
}

And the ways to call said methods:

callingMethod() {
   Bar1.getFoo().doSomething(); // Version 1
   Bar2.doSomething();          // Version 2
}

At first blush, version 1 seems a bit simpler, and follows the "rule of Demeter", hide Foo's implementation, etc, etc. But this ties any changes in Foo to Bar. For example, if a parameter is added to doSomething, then we have:

class Foo {
    void  doSomething(int x) { /* whatever */ }
}

class Bar1 {
    private static Foo _foo = new Foo();
    public static Foo getFoo() { return _foo; }
}

class Bar2 {
    private static Foo _foo = new Foo();
    public static void doSomething(int x) { _foo.doSomething(x); }
}

callingMethod() {
   Bar1.getFoo().doSomething(5); // Version 1
   Bar2.doSomething(5);          // Version 2
}

In both versions, Foo and callingMethod need to be changed, but in Version 2, Bar also needs to be changed. Can someone explain the advantage of having a wrapper/facade (with the exception of adapters or wrapping an external API or exposing an internal one).

© Stack Overflow or respective owner

Related posts about law-of-demeter

Related posts about anti-patterns