Downsizing the delegate/composition pattern ceremony

Nir Lisker nlisker at gmail.com
Wed Aug 5 21:11:36 UTC 2020


Hi,

An alternative to inheritance is the delegate pattern in which our class
holds an instance as a field and delegates its method calls to the field.
In many cases, we should prefer composition over inheritance (item 18 in
Effective Java 3rd ed.). However, the language doesn't let us do this
without pain. While with inheritance everything comes wired for us using
one `extends` word, with composition we need to rewrite method by method.
What's more, the methods' implementation is trivial and uninteresting:

class MapWrapper<K, V> {

    private final Map<K, V> map = ...

    public void put(K key, V value) {
        map.put(k, v);
    }

    public void remove(K key, V value) {
        map.remove(k, v);
    }

    // etc.
}

This results in a lot of code which doesn't tell us much. Lombok has
the @Delegate annotation that can really help in some cases, but like with
most Amber features, we prefer something that lets us express our intention
more than something that just generates the boilerplate for us.

Are there any plans or discussions concerning this?

- Nir


More information about the amber-dev mailing list