Software Design/Don't use get- prefix in the name of an expensive function

From Wikiversity
Jump to navigation Jump to search

Checklist questions:

  • Names of expensive functions start with compute-, prepare-, etc., but not with get-?
  • Names of functions that access "external" state (via RPC calls, reading from disk, querying a database, etc.) start with retrieve-, query-, etc., but not with get-?

Why[edit | edit source]

Programmers are used to thinking of functions whose names start with "get" as cheap accessors to some state. Therefore, if an expensive function is called getSomething developers might use it mindlessly in a loop or on the hot path of some other function, thus introducing a performance bug. Requiring developers to be very careful to not blow up the performance of the system is a form of fragility in code.

You can use the following prefixes instead of get- to indicate that a function performs some computations: compute-, calculate-, prepare-, count-, determine-, acquire-, extract-, parse-, obtain-, etc. Prefixes such as retrieve-, request-, download-, query-, and read- may indicate that a function reads the data from disk, or accesses a database, or performs an RPC call or a request to some REST API to prepare the result, so a call to the function may take a long time.

For example, if there is a class representing a histogram, a function that sums the data in the buckets and computes the mean value may better be called computeMean() than getMean(), according to this practice.

If get- prefixes are not used in the project, but rather getter functions' names are the same as the names of the accessed properties (for example, function foo() is used to accessed foo property), the same principle applies: names of expensive or slow functions should look different (have an unusual prefix) from names of cheap getters.

Why not[edit | edit source]

Usage of prefixes such as compute-, prepare-, extract- exposes functions' implementation details (specifically, that the function is not cheap), thus making the software harder to change without either breaking the API or making the functions' names misleading. If the implementation of a function changes and it becomes a cheap getter the function's name becomes misleading. In the histogram example above, the implementation of the histogram class may be changed so that the mean is stored in a field. Therefore, this practice should be used less eagerly in public APIs and more freely in private APIs which can be easily changed. In public APIs, function's name can still communicate non-trivial cost when it's unimaginable that the implementation may change so that the function becomes a cheap getter.

Related Practices[edit | edit source]

Sources[edit | edit source]

  • Boswell, Dustin; Foucher, Trevor (2011). The Art of Readable Code. ISBN 978-0596802295.  Chapter 3, section "Matching Expectations of Users"