Exception or soft return values?

We saw that a possible way to simplify clients’ lives is to make your method return a “soft value” instead of throwing an exception. Go back to listing 4.5 for an example.

My rule of thumb is the following:

  • If it is behavior that should not happen, and clients would not know what to do with it, I throw an exception. That would be the case with the calculateTax method. If a negative value comes in, that is unexpected behavior, and we should halt the program rather than let it make bad calculations. The monitoring systems will catch the exception, and we will debug the case.
  • On the other hand, if I can see a soft return for the client method that would allow the client to keep working, I go for it. Imagine a utility method that trims a string. A pre-condition of this method could be that it does not accept null strings. But returning an empty string in case of a null is a soft return that clients can deal with.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *