Hacker News new | ask | show | jobs
by izzle49 3920 days ago
Please don't use Java 8's default methods in interface's to do multiple inheritance, and code reuse. Prefering this over 'Util' classes is bad as it is inheritance over composition. The default methods were designed to facilitate easier interface migration
3 comments

That reminds me of "constant interface" anti-pattern - abusing a feature because it brings a small technical benefit.

If you are unhappy with candy-shop utils class and are ready to split them into smaller entities, go the whole way there. Create proper small classes, and inject them using your chose DI technology.

Anyway, kudos to the author, that was a risky article to put together and there was no way to write it without controversial recommendations. That's a good start for what a new java developer need to look for.

Inheritance over composition. I know what these words mean, but I don't see your meaning.

Also, I don't think that's what default methods are for. The new StreamUtil libraries uses default interfaces. It's not migrating anyone, but the default methods describe intrinsic properties about the classes that inherit the interface. A predicate can be in sequence of another predicate, for example.

Java was designed for TV set-top boxes, but that doesn't mean it's bad to use it on a server. If using a default method in an unintended way leads to clearer, more maintainable code, do it.
how would it lead to more clearer code? You would have many interfaces referencing an instance variable, each with different semantics for that variable. Interfaces cant have variables so they should not be used as traits.
One good use case I can see is where you want to add convenience "helper" methods to an interface that can reasonably have default implementations in terms of some other method on the interface (E.g. overloads to emulate default parameters). Or for methods that can be implemented in terms of another method, but might have a more performant direct implementation (e.g. Collection#get can be defined in terms of iteration).

I don't quite understand your point about instance variables. Instance variables are and should be encapsulated. An object that implements multiple interfaces must of course provide the correct semantics for all of them. But that's true whether an interface contains method implementations or not.