Software Design/Call function's return variable "result"

From Wikiversity
Jump to navigation Jump to search

Checklist questions:

  • Function's result variable is called result?
  • Function's result variable name starts with result-?

Why[edit | edit source]

When there is a variable called result (or res, r, etc.) in a function, it's harder to make a mistake by accidentally returning a wrong variable because it's expected that the return statement will look like return result.

When this practice is a convention in a codebase which is followed consistently, always naming the result variable result becomes a form of structure in the code. Readers can grasp functions' logic quicker by recognizing appearances of result in the code. This convention is used by Martin Fowler.[1]

Why not[edit | edit source]

As described in practice Avoid a variable called "result", naming the return variable result is a missed opportunity to attach semantic information to the variable. In relatively longer functions, readers may need to deduce or to return to the function's declaration and the documentation to recall what is returned from the function. Thus, a return variable called result makes the code of the function less obvious and makes readers navigate more.

Combining the approaches[edit | edit source]

A compromise solution is to call functions' result variables resultSemanticName, for example, resultDiscountDecimal in getDiscountPlatinumLoyalityForAccessories() function in the opposite practice.

Related practices[edit | edit source]

References[edit | edit source]

  1. Refactoring: Improving the Design of Existing Code (2 ed.). 2018. ISBN 978-0134757599.