Return Values and Observable Side Effects

Identify the result delivered to the caller and the changes a call makes to its surroundings.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Follow both outcomes
  2. Split a useful calculation from presentation
  3. Trace both a returned answer and a change
  4. Arrange effects at a clearly named boundary

Follow both outcomes

A call can yield a value, modify an object, or interact with an external resource. Printing a line changes the output stream. Assigning the result of print("ready") gives the receiving name the value None in Python. Expressions and statements help explain why a call can be used for its effect even when its return value is discarded.

Split a useful calculation from presentation

A receipt formatter can receive two prices and return the string "Total: 14". The caller can compare that result in a test, return it to another caller, or print it. If the formatter prints internally, tests have to capture the output and other callers have less choice. Specify which behavior matters in the function contract.[1][2]

Trace both a returned answer and a change

A quotation routine might receive a list of items, calculate a total, and write a progress message. The total is returned to its caller. The message goes to output independently of that return. If the routine also sorts the supplied list in place, any other name referring to that list observes the new order. A caller comparing only returned totals would miss the effect of rearranging the source.

Try a tiny input with two rows in a meaningful order, such as entries for a withdrawal and later deposit. Compute the total and assert that it equals the expected amount. Separately assert whether the row order should be preserved. Use a fresh fixture for each run so changed ordering from an earlier test cannot make the next one misleading.

Arrange effects at a clearly named boundary

A useful split can expose one calculation that returns the total and another operation that decides what to print or store. A terminal command can print the total, a service can return it in a response, and a test can compare the same numerical result. If printing is itself part of the documented behavior, test that behavior with captured output in addition to checking the calculation.

Some effects survive failure. A function can send a notification and then throw before returning its value. The caller sees the failure yet the notification already exists. Test the actual promised recovery, including whether repeating the action can send it twice. Retry-safe contracts give a concrete way to reason about that case.

References

  1. Python Software Foundation, Python Language Reference: Execution Model ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩