liveBook · Manning

Side effect

As explained in The Well-Grounded Rubyist, Fourth Edition

A side effect is an observable consequence of evaluating code beyond producing its direct return value, such as mutating state or raising an exception.

A side effect is anything a method does beyond returning a value. Mutating an object, printing output, and raising an exception are all side effects; they may be intentional or accidental. section 16.1.1

A summation that consumes its input

This method sums an array by removing its elements with shift. The first call can return the expected sum, but it leaves the array empty, so a later call returns a different result. section 16.1.1

def sum_of_parts(arr)
  sum = 0
  arr.size.times { sum = sum + arr.shift }
  sum
end

The method changes the array it receives while accumulating the sum. section 16.1.1

Using reduce instead avoids changing the input array, so repeated calls return the same result. Other Ruby methods mutate in place too: upcase! changes a string, while array append with << and hash deletion can change state without a bang suffix. Exceptions and console output are side effects as well. Side effects are not always wrong—programs sometimes need to change state—but recognizing them helps distinguish stateful methods from pure ones. section 16.1.1 section 16.1.3 section 7.3.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines mutation, output, and exceptions, then contrasts destructive methods with pure reductions; it does not prescribe eliminating all state.
Examples
Compares Array#shift and reduce, String#upcase and upcase!, array append, hash deletion, and console output.
What you can do after
Diagnose state changes and other observable behavior by checking return values, mutated objects, and raised exceptions.
How it connects
Connects side effects to pure functions, referential transparency, mutation, exceptions, and method chaining.

Also explained in

Compare how 24 books explain side effect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.