Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Builder pattern for methods with exception handling

I have a couple of methods that look like this:

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);

And so on, there are about a dozens method that does basically the same but with varying parameters.

Now I thought about using a builder pattern that would allow me to use the functionality like this:

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

However, the problem is that one of the dozens of methods throws an exception. If I use a builder pattern, then do() will have to throw this exception and therefore all clients will have to handle it. In my opinion, this sounds like a problem.

My question:

  • Is this a problem?
  • If it is, how can it be avoided?
like image 609
Fischer Ludrian Avatar asked Jul 19 '17 11:07

Fischer Ludrian


1 Answers

Yes. It is a problem.

You may:

  1. Catch the exception if you know how to handle it and if the field to be set is optional.

  2. But if the exception gets thrown when you try to set a mandatory field then it means something is wrong and the whole operation should fail.

like image 127
ACV Avatar answered Sep 22 '22 13:09

ACV