Author: Brandon Pearman

The views expressed here are mine alone and do not reflect the view of my employer.

A side effect is when there are changes to the state of the application.

eg a function which opens a connection to a db puts the application in a state where it can query the database. The open connection function had a side effect.

Side effects include changes to:

  • global variables
  • class variables
  • databases
  • files
  • connections

Unexpected Side effects

Side effects dont seem so bad until there are so many you can't keep track of what is changing what, or changes are happening which you did not expect. For example if you call the function GetDetails(); you probably wouldn't expect changes to class variables or to the db. These unexpected side effects cause code to be fragile. Does the below function check if "USA" was set or does it set "USA" and return if successful.


Excessive Side effects

The more state and side effects your application has to deal with the harder it becomes to reason about the code by simply reading it. When an application has excessive state and side effects, then the best way (or sometimes the only way) to understand the code is to run it and watch what it does.

For example compare:

  • A class which has no state and every function output is determined purely from its input.
  • A class which has one hundred different variables which need to be checked and changed by multiple different methods, the output of a function is determined by the input and numerous shared varibables which are modified by an unknown amount of other functions.

When there is no state or side effects the application is predictable and results can easily be reproduced. But side effects are normally required by a system for it to do anything of value. We can try eliminate as much side effects as possible but where we can't we must make them clear and contained.

Check out these links for more info:

My design and architecture repo