Side effects

Don't touch external world!

Side effects

Don't touch external world!

What is a side effect?

What is a side effect? Let’s take a simple function that computes the absolute value of a number and prints it in a simple console application:

def abs_value(x):
   if x < 0:
       return -x
   return x

if __name__ == '__main__':
   number = int(input("enter a number:"))
   print("Absolute value is", abs_value(number))

Here, x is a function’s argument, and what comes out from the return statement is called a “primary effect”.

Now let’s take a look at another function:

def abs_value_2(x):
   if x < 0:
       return -x

   twitter_api = TwitterAPI(random_twitter_id())
   chat_bot = LanguageModel()
   tweet_content = twitter_api.read_first_tweet()
   _ = chat_bot.parse(tweet_content)
   response = chat_bot.make_response(
       f"{x} is important because ")
   twitter_api.respond(response)
   twitter_api.close()

   return x


if __name__ == '__main__':
   number = int(input("enter a number:"))
   print("Absolute value is", abs_value_2(number))

Here we also have the same primary effect returned by the abs_value_2 function. But now we have a section in the middle that performs pretty surprising actions, to say the least. When you want to compute abs of a negative x, a language model chooses a random tweet and leaves its valuable opinion about it. It is an example of a “side-effect”: abs_value_2 has additional means to influence the external world.

You may ask: “Why do you have a weird unrelated piece of code in your function??” Obviously, it’s a contrived example, but people experienced with large codebases might relate to it. It’s just a set of refactorings, misunderstandings, and a stream of people joining and leaving teams: time passes, and simple code accumulates unrelated baggage.

Here are some real examples of side effects that I’ve encountered:

  • publishing a number to the Weights-and-Biases server out of the loss function
  • dumping debug images into /tmp from a computer vision algorithm
  • changing an environmental variable inside a function
  • dropping to pdb on if condition
  • changing a global variable
  • calling sys.exit inside an algorithm
  • sending a Slack message if nan is encountered during a backpropagation
  • &mldr; and so on.

Side effects are unavoidable because any software must have at least some influence on the external world. Otherwise, what’s the point of running it?

But are side effects bad? After all, the user experience is not different between the first and the second implementation of abs_value. If your job was to write a script according to a simple specification: “Output the absolute value of an entered number,” then both scripts conform to it. Your boss and a product manager will be equally satisfied by both deliverables (at least initially).

If there are no visible differences, is there a reason to prefer one script over another? What are the generic downsides of side effects?

Unexpected crashes

How can abs_value crash? It pretty much can’t. Unless there is an interpreter or some system problem, this function will always work as advertised.

What about abs_value_2? It might crash in almost every line:

  • a Twitter API might fail to initialize
  • a language model can’t allocate GPU memory
  • it might fail to parse or generate a phrase
  • a Twitter API might fail to publish a response or crash on closing

In real-world code, every line with side effects might crash because it typically deals with an external thing you do not have control over. From the examples above:

  • Weights-and-Biases or Slack might be unavailable
  • you might run out of space in /tmp
  • environmental variable is deleted before setting
  • &mldr; and so on.

So the code with side effects is more fragile.

Unexpectedly slow (and occasionally very slow) code

Every side effect typically brings computational costs. But most importantly, it brings timing variability into your software. Because side-effect code typically deals with uncontrolled external resources, you get uncontrolled slowdowns. Every side-effect code line in abs_value_2 can bring you a massive slowdown:

  • a Twitter API could be slow to connect
  • a language model might wait for free GPU memory
  • computational load on the system might make phrase parsing too slow

In real-world code, similar things can happen:

  • database access could be very slow because the network is busy
  • writing to a hard drive could be slow because of fragmentation
  • logging could be too slow because other loggers compete for file access
  • &mldr; and so on.

The bottom line is that the code with side effects is slower. Just those two reasons: a higher chance of crashing and being slow might already change the mind of your boss and a product manager from neutral to “we can’t release abs_value_2!”

But there are several more downsides to the code with side effects.

Side effects are hard to understand

What if I ask you to write a docstring for abs_value_2? You will definitely struggle to write a concise story about the purpose of that function. Similarly, if you just read the code with side effects for the first time, you will not understand what the heck is going on.

A function with a single return statement achieves a single result, so you can concisely formulate a docstring as

```This function computes <something>.```
If there are side effects, you have to add them all one by one:
```This function computes <something>, 
AND it logs images to the hard drive, 
AND sends a Slack message on failure 
AND sends <something> to the main process.
```
In a large company, many people are joining and changing teams. A company with less-readable code will waste days of cumulative onboarding time on understanding obscure functions (even if they work flawlessly). A large docstring is not going to help because the bigger the doc, the greater the chance it will be ignored completely.

Side effects are hard to debug

Because the code with side effects interacts with stuff that is not under your direct control, you will have many unpredictable and stochastic failures that are very hard to debug. For example, after considering all the reasons to crash in the function abs_value_2, you might still find that it occasionally crashes after the release, and you just can’t reproduce a single crash in-house (e.g., maybe when your script runs on Windows Vista, GPU kernels behave differently?).

There is a crazy variability in the external world, so it is very hard to reproduce, debug and fix all edge cases of side effects.

Side effects are hard to test

For all the same reasons, it is almost impossible to write exhaustive unit tests for code with side effects. On top of the main result, you should better test that all side effects behave as expected: did the person get a tweet? Was the tweet parsed correctly?

Not to say of some weird unit test interactions: side effects from one test could make other tests fail. For example, one test can set a global variable that another test uses to evaluate something.

Also, it is often impossible to actually interact with the external world on a test server, so developers have to resort to mocking all external entities.

Code with side effects is hard to reuse

What if your colleague wants to compute the absolute value of a number? There is no problem with abs_value. You just import the function and use it! What about abs_value_2? Looking at the function name, they wouldn’t know a priori if there are any side effects. But after noticing those weird code lines and anticipating all the problems we mentioned, they might just leave such a function alone and write their own simpler implementation.

Often developers don’t even notice side effects. The code can happily work until some unfortunate day when all the crazy issues we mentioned start coming up: the code begins to crash and make everything slow. After finding the root cause, people might be tempted to re-implement the function from scratch.

At the end of the day, a codebase that relies on side effects would typically have much less code reuse.

Conclusion

Hopefully, you’re convinced that side effects are also the root of all evil (just like premature optimization). Code with side effects is fragile, slow, hard to understand, debug, test, and reuse. Unfortunately, there is no way to avoid side effects, but we can minimize them, which is a topic of the next post. Meanwhile, thank you for reading!


See also

comments powered by Disqus