Stream: helpdesk (published)

Topic: Advice on constructor style


view this post on Zulip mbaz (Mar 24 2023 at 17:08):

Consider a package that keeps some state consisting of objects of type Object. New objects are instantiated and given an ID with Object(ID).

Users can select a particular object. This can be done in at least two ways:

  1. Let Object(ID) return the existing object if ID already exists and a new object otherwise.
  2. Restrict Object(ID) to be a true constructor, which can only create new objects, and use another function (say) object(ID) to select existing objects.

Which is better? Method 2 is arguably "purer" and more elegant, since constructors are used only to construct, but it probably requires more mental effort from users ("am I constructing or am I selecting?")

view this post on Zulip Expanding Man (Mar 24 2023 at 17:21):

As I recall, the Julia documentation hints that Object is expected to return a new object, but there are certainly packages around in the ecosystem that use constructors to access existing objects. I myself have occasionally used them as "getters", though if I thought more carefully about it I'd probably regret that practice (get(x, ::Type{Object}) seems better). I think option 2 is probably better.


Last updated: Nov 06 2024 at 04:40 UTC