[英]How to separate interface from technical implementation using Interfaces when there are Exceptions
I try to separate the technical implementation and the domain logic interface using Java interfaces.我尝试使用 Java 接口将技术实现和域逻辑接口分开。
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.
.因为2.
我也必须在接口方法声明中添加 'throws',这与要求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.例如,您可能有一个 UserRepository 接口,而您的实现目前正在使用 SQL 来查找用户。 You can mark your interface methods as throwing your own exception types (eg UserNotFoundException
).您可以将您的接口方法标记为抛出您自己的异常类型(例如UserNotFoundException
)。 Your implementation catches any SQL-related errors and throws a UserNotFoundException
instead.您的实现会捕获任何与 SQL 相关的错误并抛出UserNotFoundException
。
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.这样,如果您将来切换到使用 MongoDb 或其他东西,您的界面将保持完全相同,而您的实现现在必须捕获 MongoDb 抛出的异常类型。 The code that consumes your interface continues to work correctly because it knew how to handle the UserNotFoundException
already, and that hasn't changed.使用您的界面的代码继续正常工作,因为它已经知道如何处理UserNotFoundException
并且没有改变。
Remember to include the original exception as the cause
of the new exception you're throwing so as not to lose the stack trace.请记住将原始异常作为您抛出的新异常的cause
,以免丢失堆栈跟踪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.