检查异常规范和策略模式 [英] Checked exception specification and strategy pattern

查看:123
本文介绍了检查异常规范和策略模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个c ++开发人员,我在java中已经被检查和未被检查的异常非常新鲜。 c ++中的异常规范根本不好,这就是为什么没有人使用它。我喜欢被检查的异常,我有一个问题,让我们有这个界面:

  public interface Warehouse {
MyStuff fetch (int id);
}

仓库可以以不同的方式实现:文件,数据库或内存(现在,如果我想实现使用一个文件,我不能尝试在方法中打开该文件,否则我的签名将改变,我的类将不再实现接口了。另外如果我有另外一个类有另一个被检查的异常,所有其他现有的实现将受到影响。



我可以看到两个解决方案:


  1. 捕获已检查的异常并抛出另一个自定义运行时异常。我不认为这是一个很好的解决方案,为什么用户应该捕获一个运行时异常,当有已经有标准和检查的方式时,文件丢失了。


  2. 在实现类的构造函数中执行整个作业,并使fetch函数无法抛出。我喜欢这样,对象既存在又是有效的,或者不存在。这种方法的唯一缺点是我们不能执行懒惰的评估;我们需要在构造函数中读取和解析文件,即使没有人会使用该对象。这不是有效的。


我错过了什么?有没有更好的方法来避免这个问题?

解决方案

你的第一个解决方案是正确的。将您的界面更改为:

  public interface Warehouse {
MyStuff fetch(int id)throws FetchFailureException;
}

并使每个子类将其IO,JDBC或任何异常包装在FetchFailureException中。如果不可恢复,则FetchFailureException异常应为运行时,并检查是否可恢复。


I am a c++ developer and I am pretty new with the checked and unchecked exception in java. The exception specifications in c++ are simply not good and that's why nobody is using it. I like the checked exception and I have a question, let's have this interface:

public interface Warehouse {
   MyStuff fetch(int id);
}

The warehouse can be implemented in different way: file, database or in memory (mock object for test).

Now, if I want to implement using a file, I cannot try to open the file in the method otherwise my signature will change and my class will not implement the interface anymore. Also if I had another class with another checked exception all the other existing implementation will be affected.

I can see two solutions:

  1. Catch the checked exception and throw another custom runtime exception. I don’t think this is a good solution, why the user should catch a runtime exception saying that a file is missing when there is already a standard and checked way to do that.

  2. Do the entire job in the constructor of the implementation class and leave the fetch function unable to throw. I like this way, the object both exists and is valid or it doesn’t exist. The only drawback on this approach is that we cannot implement a lazy evaluation; we need to read and parse the file in the constructor even though nobody will use the object. This is not efficient.

Am I missing something? Is there a better way to avoid this problem?

解决方案

Your first solution is the right one. Change your interface to :

public interface Warehouse {
    MyStuff fetch(int id) throws FetchFailureException;
}

And make every subclass wrap its IO, JDBC or whatever exception inside a FetchFailureException. This FetchFailureException exception should be runtime if unrecoverable, and checked if recoverable.

这篇关于检查异常规范和策略模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆