r/java Sep 19 '18

JEP draft: Concise Method Bodies

http://openjdk.java.net/jeps/8209434
58 Upvotes

51 comments sorted by

View all comments

2

u/daniu Sep 19 '18 edited Sep 19 '18

Sure, getters and setters are somewhat shorter by this, but if you're annoyed by those and not using Lombok I can only assume it's due to your company policy. I can't see how non-trivial methods gain a lot by being able to remove the braces surrounding the body. Not that I'm against the introduction of this feature, it does make it more consistent with the lambda stuff, but I don't see it as a huge improvement.

class MyList<T> implements List<T> {

   private List<T> aList;

   public int size() = aList::size;
   public T get(int index) = aList::get;
   ...
}

That's actually kind of common - delegating the implementation of an interface to a member. But it's not really that much less boilerplate if you still have to delegate on a method level - there could be something like

class DelegatingList<T> implements List<T> {
    // 'delegate' meaning all non-implemented List methods are created for this class and delegated to aList
    private delegate List<T> aList;

    public void add(T item) {
        // still able to implement specific methods of the interface yourself
        aList.add(item);
    }
}

1

u/yawkat Sep 20 '18

This sort of delegation has all the problems normal extension has, except for being able to swap out impl. Don't do it, even though lombok allows you to.

I wrote on the problems with extending like that a while ago: https://javachannel.org/posts/how-not-to-extend-standard-collection-classes/ - the proper solution is to just exhaustively implement abstractlist.