简体   繁体   中英

How to separate interface from technical implementation using Interfaces when there are Exceptions

  1. I try to separate the technical implementation and the domain logic interface using Java interfaces.

  2. As I also do test driven development, my implementations have to throw exceptions, which are related to technical problems.

Because of 2. I have to add 'throws' to the interface method declarations too, which clashes with the requirement 1. .

So my problem is, that I don't want to have implementation specific details in the interface but I want to do test driven development.

My first idea to solve this, is to translate technical exceptions to domain logic exceptions.

Is this the only way to go or do I miss something? Is there an approved design pattern to solve this or any other solution to this problem, because to introduce a lot of custom exceptions will lead to an overhead in development.

The typical way to solve this problem is to catch the implementation-detail Exception types, and throw a new exception type which is more appropriate to your specific service. If this is what you meant by "translate technical exceptions to domain logic exceptions, then yes, that's the right way to go.

For example, maybe you have a UserRepository interface, and your implementation is currently using SQL to look up the users. You can mark your interface methods as throwing your own exception types (eg UserNotFoundException ). Your implementation catches any SQL-related errors and throws a UserNotFoundException instead.

This way, if you switch to using MongoDb or something in the future, your interface stays exactly the same, while your implementation now has to catch the kinds of exceptions that MongoDb throws. The code that consumes your interface continues to work correctly because it knew how to handle the UserNotFoundException already, and that hasn't changed.

Remember to include the original exception as the cause of the new exception you're throwing so as not to lose the stack trace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM