On Getters and Setters, or Mutator Methods

Getter and setters - less commonly known as mutator methods - are as essential a part of Swift as they are of any modern language. But I find the verbs chosen to label them either inconsistent, or inaccurate, or both. "Set" is obviously chosen as it rhymes with "get," which is sensible enough, except that "get" itself isn't ideal in the first place. "Getting" something suggests the object is close at hand. Within the confines of an app, "getting" makes sense, but stepping beyond that seems inappropriate. Instead, I would suggest that the following makes sense, for different contexts:

Getting and setting locally remains fine. When deleting properties locally, they are almost always set to null, so annul is more accurate than delete. Likewise add and remove are sensible when referencing collections, and like get, gather starts with a "g," and implies retrieving multiple items. retrieve and store are reminiscent of household chores, and one's device is one's digital home, and delete suggests that it's gone, but not forever, assuming the data exists elsewhere. fetch and save are appropriate for data stored in databases as they suggest a certain distance to the data, and destroy really does underline that once a property stored in a database is deleted, it is gone forever. resolve underlines that when querying an API etc., one can never really know what one is going to get back: useful data; a successful flag; a network error. It's just impossible to know. So call an API via a function named something like resolve( Username ), and send the callback to a function named something like onUsernameResolved, where it's payload can be assessed.

I imagine there will be readers who find this pedantic, or some other flavour of pointless, phrases like GET are already enshrined in, say, query language traditions, so why change something that isn't broken? Two reasons:

  1. Tradition is bullshit. It was once traditional to pour one's faeces out of the window, but once we learned that was suboptimal, we stopped it; and
  2. when one starts a function with one of these verbs, because they are all different it shows the programmer immediately what manipulation that function is going to perform: it will get, set, or delete data - sure - but it is also clear where and how the manipulation will take place. The expressive strength of each verb increases with increasingly serious actions:

And if the style of the three functions listed immediately above seems strange to you, please see my post on splitting function names.

Leave a Reply

Your email address will not be published. Required fields are marked *