Should a method (remote method call) return a boolean true value indicating that an operation performed successfully even if all possible exceptions are thrown?

Example:

In my java application have many CRUD remote method calls and I catch all possible Exceptions and throw a Custom Exception to the calling client.

Should I now return void or a boolean, since the Exceptions already implicitly indicate the success or failure of the operation?

有帮助吗?

解决方案

Return void, not a boolean in this case.

Exceptions are for exceptional conditions. Why indicating something like the success or failure of an operation on two different channels? The DRY principle teaches us:

Don't repeat yourself

I would only use a boolean to indicate further information, like it is sometimes done on collections, reporting whether an item was found for removal.

其他提示

I suggest returning void.

If you return a boolean, the calling code has to guess "Oh, should I check the boolean or check the Exception? Or maybe do both?"

When using exceptions for all error conditions, only return a value if the method has actual useful data to return.

If you have no useful information to return, use void.

I think this is a matter of convenience. The fact that you already throw a custom exception helps identify the exact error if there is one.

But, sometimes, you might find it convenient to use expressions like:

  if(method()){
     ... 
  }

So, returning a boolean might be useful.

In the end, the two (throwing an exception and returning a boolean) don't exclude each other

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top