Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface with inner implementation - good or bad [closed]

I am working on a project with many someInterface - someInterfaceImpl-pairs. Some days ago I got the idea (probably inspired by reading some objective c code) to include the default implementations as an inner class. Now some colleagues (all with much more java experience than me) saw this idea - feedback was between shocked and surprised ("this is working?").

I googled around a bit but didn't find much evidence of usefulness of this "pattern" (personal i like it): pdf-paper and a faq about code style

What do you think - especially in those cases where an "default" implementation is tightly coupled to an interface.

Update i just found this: Java Interface-Implementation Pair

(see accepted answer)

like image 644
dermoritz Avatar asked Nov 28 '25 02:11

dermoritz


1 Answers

The whole point of interfaces is to separate the users from the implementation (default or not). You defeat this by including the implementation as an inner class. You don't really save any lines of code and you clutter the API. You end up having to do things to hide the inner class from the users of the interface like making it private or default scope which it might be better to avoid. Also, what if your default implementation needs to change but you have published the interface as part of an API. This is a bad idea in that it does not have a lot of benefit and is an anti-pattern.

Finally, if you REALLY have a default implementation then maybe that should be a base class (rather than an interface) and other implementation extend the class and override behavior.

I thought this post gives an interesting discussion of a similar question: Question

like image 157
John B Avatar answered Nov 30 '25 16:11

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!