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:
Object(ID)
return the existing object if ID
already exists and a new object otherwise.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?")
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