Hacker News new | ask | show | jobs
by dcow 1864 days ago
Last time I wrote Java was before it had nice things so I may be slightly out of date in my assessment of its verbosity. I really wish it had decorator syntax like Kotlin does:

    class Foo(val delegate: Collection) : Collection by delegate
    {
        override fun length() = delegate.length() + 42
    }

    val foo = Foo(delegate: LinkedList())
    foo.add(1)
    foo.add(2)
    for e in foo {
        print(e)
    }
    foo.removeAll()
    foo.length() // = 42
I think a lot of the verbosity I remember was due to the sheer size of the type of interfaces you'd encounter in practice and an inability to easily compose them without implementing your own set of forwarding decorators (io stream style). That and getters/setters or rather the lack of any language-level support for dynamic properties.
1 comments

Do you really want to inherit all the functions of Collection? Isn't this the anti-pattern everyone complains about on inheritance vs composition? This just looks like it's confused about whether it is a collection or has a collection.

Personally, I'd just rather take a collection by composition and only expose the small part of the API I actually want.

I guess though this is the standard decorator pattern you'd normally see from GoF.

It also breaks LSP when you “extend but reduce”. Not saying there aren't uses for “have-a”. More that writing a decorator in Java is awful.