concept environment in category swift

appears as: environment
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

A predictable state prevents the environment from being in limbo between an error state and a sort-of-okay state. Keeping an application in a predictable state means that when a function or method throws an error, it should prevent, or undo, any changes that it has done to the environment or instance.

Let’s say you own a memory cache, and you want to store a value to this cache via a method. If this method throws an error, you probably expect your value not to be cached. If the function keeps the value in memory on an error, however, an external retry mechanism may even cause the system to run out of memory. The goal is to get the environment back to normal when throwing errors so the caller can retry or continue in other ways.

The easiest way to prevent throwing functions from mutating the environment is if functions don’t even change the environment in the first place. Making a function immutable is one way to achieve this. Immutable functions and methods have benefits in general, but even more so when a function is throwing.