Programming Proverbs 8: Avoid side effects

Side effects are actions that change things outside of a procedure, function or method. Generally this happens when a procedure modifies a global variable. I’m tempted to suggest that this proverb might just as well be “avoid unnecessary global variables.”

The problem here is that since the activity is not clearly in the functions description or prototype it is far too easy to forget (or not know in the first place) that it is taking place. This makes debugging the problems that it inevitably causes quite difficult.

These days good programmers tend to avoid global variables. Global constants which cannot be changed are very valuable and safe. But you really want to avoid directly changing anything outside the scope of the local method.

This is the eighth of a series of posts based on the book Programming Proverbs by Henry Ledgard. The index for the series is an earlier post and discussion of the list as a whole is taking place in the comments there. Comments on this “proverb” are of course very welcome here.

Comments (1)

  1. Adam says:

    I would argue that another incarnation of "side-effects" is when a function performs something additional that is non-obvious from its signature/contract.

    e.g. a function called CalculatePrice takes a list of products as an argument… you would expect it just calculates the total price of all the products, but it goes and decrements the inventory count for each product as well… bad form, old chap.