Throw an exception in the default interface method

I recently came across this code.

public interface CustomerQueryService { default Customer getCustomerById(long id) { throw new NotImplementedException(); } } 

Later it turned out that this is a general convention for this project. Is this considered good practice?

+5
source share
2 answers

One could start here to find out that Brian Goetz, one of Java's “active fathers,” must say “how to use default methods.”

So, according to the "books"; you can use them, as in your example: throw an exception for a method that is considered "optional." But that will mean: you already have some methods; and you add new ones.

The main goal of adding default methods to the Java language was to allow inextricable improvements to existing interfaces. They were not intended to be used as a kind of "mixin" / multi-inheritance / traits-like, providing a construct.

But beyond that: in your example, you have a new interface ... that has only this one method. I think this does not fall under these “intended uses”.

On the other hand; not too much about books. When a whole team of people agrees “this is what we do,” and everyone understands and buys about it; why not?!

But there is one caveat ... my C ++ employees have a strict policy: they allow the implementation of any one abstract method in the inheritance tree; since it is very difficult to debug a problem when you look at the implementation of an incorrect method. And now that we can inherit the default methods in Java, too ... debugging problems can get complicated for Java in the same way. Therefore, be careful how such things are used!

In short: it's good practice if most of your development team finds it a good practice. If not, it is not.

+10
source

I would say that this is bad due to the type of exception and reports that this is an agreement in the project.

NotImplementedException :

NotImplementedException represents a case where the author has yet to implement logic at this point in the program. This can act as an exception-based TODO tag.

So, this is a lazy way to ensure that the method is implemented in all CustomerQueryService just to find out at runtime that you haven't written it yet.

Note UnsupportedOperationException may be acceptable in some cases, but none of them will be a good “convention” for the project.

+6
source

Source: https://habr.com/ru/post/1264514/


All Articles