If you enjoy reading these exercises then please buy Crista’s book to support her work.
Style 22 – Passive Aggressive
- Every single procedure and function checks the sanity of its arguments and refuses to continue when the arguments are unreasonable, jumping out of the function.
- When calling out other functions, program functions only check for errors if they are in a position to react meaningfully.
- Error handling occurs at higher levels of function call chains, wherever it is meaningul to do so.
We have seen two contrasting approaches to handling exceptions recently:
- Constructivist style where we always provide fallback values to allow program to continue
- Tantrum style where we always throw exceptions to terminate program right away
Despite their different responses to exceptions, both styles share something in common – that they deal with exceptions at the callsite. Today’s style differs in this regard. Here, we’ll only consider the happy path and allow exceptions (that we can’t deal with meaningfully in the function) to escape and bubble up to a function that’s higher up in the call chain and CAN handle it in a meaningful way.
We’ll keep the solution to the same structure as the last two styles, but notice that we’re not explicitly handling file exceptions in extractWords and removeStopWords.
However, any escaped exceptions will be handled and logged by the top-level function.
If you come from a .Net or Java background, this is probably the style that you’ll most often encounter in the wild. If you’re an Erlang developer, this style perfectly embodies Erlang’s famous Let it Crash mantra!
However, you shouldn’t confuse the Passive Aggressive style with “controlling program flow using exceptions”, which points to a specific anti-pattern, like this example.
I generally prefer the Passive Aggressive style, although it doesn’t have to be mutually exclusive to the Constructivist and Tantrum styles. For example, you might leave exception handling to a function that’s higher up in the call chain, who then in turn return a fallback value for the whole chain.
As a side note, I also discovered a while back that there’s a non-trivial performance overhead associated with throwing (lots of) exceptions (another argument against using exceptions to control program flow) as the CLR needs to collect lots of runtime diagnostic information for each exception.
And finally, another often-missed observation about exceptions is that, they are really another form of GOTO.
You can find the source code for this exercise here.