Comment by owlstuffing

5 days ago

> We now know that we prefer composition over inheritance

When people say "composition over inheritance" in Java discussions, they usually mean the trivial modeling rule: prefer has-a over is-a.

But that’s not what composition is really about.

The deeper idea is interface composition -- building types by composing multiple behavioral contracts behind a single cohesive surface.

Java provides inheritance and interfaces, but it doesn’t provide first-class delegation or traits. So most developers never really practice interface composition. They either subclass, or they wire objects together and expose the wiring.

The slogan survived. The concept mostly didn’t.

The manifold project, for example, experiments with language-level delegation to make interface composition practical with Java.

https://github.com/manifold-systems/manifold/blob/master/man...

> Java provides inheritance and interfaces, but it doesn’t provide first-class delegation or traits.

I'm not sure I am missing first class delegation much (not a lot of UI projects in Java these days).

But interfaces with default (and static) method implementations are actually quite usable as traits / mixins. Since Java 8 IIRC.

You can also pass around functions / lambdas (coincidentally also since Java 8) to compose functionality together. A bit harder to follow and/or understand, but another perfectly legitimate and very powerful tool nevertheless.

Well, what mainstream language has better tools for composition?

  • Rust with traits and Swift with protocols

    • So just type classes?

      How does a type class help with composition? They do help with the expression problem (adding support for an "interface" after definition), and via parametric polymorphism they might give you a bit with regards to composing two traits.. but you do also have generics in Java, even if not as good as type classes.

      So anyways, I don't see as big of a change here. But there was a Brian Goetz mail/presentation somewhere where he talked about adding "basically type classes" to Java? But unfortunately I couldn't find it for you now.