Exceptions and Complexity

Why Exceptions add complexity

Exceptions and Complexity

This post is originally posted at petran.substack.com

In this post, we will reveal why exceptions add complexity to an application and how to reduce the generated complexity.

This post is inspired by the book A Philosophy of Software Design

🌊Let’s dive in

Introduction

Exceptions on our code flow are critical cases that we must handle and the majority of times are non-related to the business logic.

But inside exceptions, we have to write more code and possibly it could generate more exceptions.

All these lead to increasing the complexity of the software we are building.

Blocks of code exposed on exceptions:

  • Database connections and operations
  • Network activities (REST calls, TCP connections)
  • IO activities (open a file for reading etc)
  • and many more …

How to reduce the complexity

The best way to reduce the complexity of exceptions is to reduce the number of places where exceptions have to be handled

This means that we must eliminate the number of try catch blocks to the minimum.

In addition more try catch blocks means that with have more code flows (branches) to consider, solve, test, and boilerplate code to write

number of exceptions equals complexity level

1. Define Errors out of existence

The first way to eliminate exceptions is to design and implement APIs without exposing any exceptions.

This means that any consumer of the APIs will not have to figure out how to deal with exceptions and furthermore the code will be much simpler.

2. Mask Exceptions

The second way to reduce places with exception handling is Masking Exceptions.

This technic hides the places where the systems handle exceptions on the lower levels, driving the high-level systems not worried about any of those conditions.

3. Exception Aggregation

One more way is to use Exception Aggregation and handle multiple exceptions on one single generic Exception.

With this approach, we can reduce the places where individual exceptions occur with a more simple generic Aggregated Exception.

4. Just Crash

The last approach is not to catch an Exception and drive the system to Just Crash.

We can apply this technic in cases when :

  1. It’s not worth catching and handling an exception
  2. We don’t care if the system crash
  3. We don’t know how to handle the exception
  4. When is the simplest and clean way to design and implement the system

Conclusion

All these technics help to reduce the places that handle exceptions and build software systems with low complexity

Reference :

--

--

Petros Koulianos 💀☠👽

Software Engineer 👽 | Building applications for health industry | Work with JavaScript, Typescript, PHP | My Newsletter📩 at petran.substack.com