What is a side effect?
According to Wikipedia, a function has a side effect when “it has on observable interaction with calling functions or the outside world”. Uncle Bob says that side effects are lies. A side effect happens when a function is supposed to do something, but it also does other things you don’t expect it to do. Examples of side effects can be changing the value of class or static variables, leave objects in a different and unexpected state.
A simple example (modified from the Clean Code book) is the following function
public bool CheckPassword(string userName, string password){ User user = UserGateway.FindByName(userName); if(user != null) { if(user.Password == password) { Session.Initialize(); return true; } } return false; }
The side effect in the functions is the call to the Session.Initialize() method. The function name says that it will check the passwork, but it doesn’t give any clue that it will initialize the user session if the password is correct. If someone called the method just to check the password, unnecessary user sessions could be started or valid user sessions could be overwritten.
We must always take care that our functions do not have side effects. Functions that do “extra” things you don’t expect them to have been the source of many sleepless nights for programmers everywhere.