Question

Many times, I run in a situation where I have a option to either return a bool or void. For example consider the case:

public (return_type) updateQueryStats(String ident, Double execTime) {
    Double newAvgTime;    
    //calculate average query time.
    avgTime.put(ident, newAvgTime);
    //return true;
}

Let us say that these are to be used as API or library by other users. Although both are functionally same, which one is a better practice.

Was it helpful?

Solution

If your method will always return true, and in no case a false value. Or you are just putting boolean return type to denote successful database query, I would avoid using boolean return type. You should better keep the return type as void, as technically the method wouldn't return anything. And in case of failure, you can throw an exception - Unchecked, or checked, that you can decide, based on whether you want to proceed on failure or not.

OTHER TIPS

For update queries returning Boolean make the user aware of success/failure of the operation.

if you don't want to return Boolean you can throw an exception when update operation failed

Returning a boolean could be used when you want a way to check if the operation made in the method was successful or not.

In the other hand, if you want your method to don't return anything (void), you could use try-catch clauses to handle problems.

Of course it depends on how your program is working, you must choose the way that fits better to your situation.

Although there's no hard-and-fast rule here, let me layout my personal guidelines:

  • If the net effect of the operation[1] did not take place, report the failure via an exception. This will force the caller to be aware of the failure. A return value can be silently ignored.

  • If there are two (or more) different situations[2] in which the same expected net effect can be achieved, use a boolean (or a more elaborate return type, e.g., enum) to report which of the situations was encountered.

  • Otherwise, void void.

[1] here: avgTime.get(ident) == execTime

[2] For instance, avgTime might already have a value associated with ident.

I'd definitely go for void. You can change it later if you find out that you need some return value. Such a change is much simpler than the other way round.

You may also find out that you need to return something else (e.g. newAvgTime) instead of your boolean.

Moreover, how would you document the return value?

  • Return true on success?: What is a "success"? You should throw if something goes really wrong.
  • Always return true.?: What is this good for?

Note that returning a value means you have to obtain it somehow, and this may cost performance

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top