Downsizing the delegate/composition pattern ceremony
Brian Goetz
brian.goetz at oracle.com
Thu Aug 6 14:00:10 UTC 2020
This is on our radar, but it is lower priority than some other things.
As Remi pointed out, there's a (currently dormant, again, priorities)
JEP for concise method bodies, the more interesting form of which is
something like (syntax only for exposition):
class MapWrapper<K,V> {
private final Map<K,V> map = ...
public void put(K key, V value) := map::put;
public void remove(K key, V value) := map::remove;
}
This is clearly a big improvement already over your example, but as you
commented to Remi, you would still view that as glass being "half
empty." On the other hand, this is also far more general than a feature
for "inheritance by delegation."
There are other things we can consider too, but I think we should finish
up the things we're working on first before we add new things to the list.
On 8/5/2020 5:11 PM, Nir Lisker wrote:
> 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