具有异常处理的方法的构建器模式

时间:2017-07-19 11:21:20

标签: java oop exception-handling

我有几个看起来像这样的方法:

public void do(A a, B b);

public void do(A A, C c);

public void do(D d, A a);

public void do(D d, E e, X x, F f, Optional<A> a);

依此类推,大约有几十种方法基本相同但参数不同。

现在我考虑使用一个允许我使用这样的功能的构建器模式:

withA(a).withB(b).withX(x).do();

然而,问题是数十种方法中的一种抛出异常。如果我使用构建器模式,那么do()将不得不抛出此异常,因此所有客户端都必须处理它。在我看来,这听起来像是一个问题。

我的问题:

  • 这是一个问题吗?
  • 如果是,怎么可以避免?

3 个答案:

答案 0 :(得分:1)

是。这是一个问题。

你可以:

  1. 如果您知道如何处理异常并且要设置的字段是可选的,请捕获异常。

  2. 但是,如果在尝试设置必填字段时抛出异常,则意味着出现问题,整个操作都会失败。

答案 1 :(得分:0)

总有简单的&#34;把它变成RuntimeException&#34;溶液

简单地试试/捕捉;并在catch中创建一个新的RuntimeException来包装已检查的异常 - 并重新抛出它。 javadoc中的ANd文档。

答案 2 :(得分:0)

当您将参数用作导致异常的类型时,您可以更改上下文。

请注意,这不是最明智的想法,也许不应该受到鼓励。

Sample Builders:

class ParamA{}    
class ParamB{}

class Builder {

    // ... More Stuff ...

    public Builder with(ParamA p){
        // x happens here
        return this;
    }

    public BuilderB with(ParamB p){
        // y happens here
        return new BuilderB(this);
    }

    public void doWork(){
        System.out.println("I did my stuff");
    }
}


class BuilderB{
    private BuilderB(){}

    public BuilderB(Builder b) {
        //Initialize with stuff from b
    }

    public BuilderB with(ParamB p){
        // y happens here
        return this;
    }
    public BuilderB with(ParamA p){
        // x happens here
        return this;
    }

    public void doStuff() throws Exception{
        throw new Exception("poof");
    }
}

用法:

void example() {

    ParamA a = new ParamA();
    ParamB b = new ParamB();

    // doWork in builder doesn't throw, we're good
    new Builder().with(a).with(a).doWork();

    try {
        // stuff in BuilderB trhows, surround w/ try catch
        c.new Builder().with(a).with(b).doStuff();
    } catch (Exception ex) {
        System.out.println("Exception goes " + ex.getMessage());
    }
}
相关问题