Working on two nimble libraries. The "NEP" coding style does not currently answer this post's styling questions. Some of the discussion on the forum implies that there might kind-of-sort-of be answers though.
Most of the library objects need initialization to properly work. So, the user will need it run a setup routine of some kind. Simple-to-the-point-silly example:
#
# from the module (pretend this part is in a module)
#
# import fruit
#
type
Fruit = ref object of RootObj
species*: string
meaning: int
double_meaning*: int
method setup*(self: Fruit, meaning: int) {.base.} =
self.meaning = meaning
self.double_meaning = meaning * 2
method setup*(self: Fruit) {.base.} =
self.setup(42)
#
# example of use
#
var a = Fruit(species: "apple")
a.setup()
echo $a.double_meaning
Calling the method "setup" is technically functional. It implies that it should be run once (and only once) after the Fruit object is instanced.
The questions:
1. Is there an ideal idiomatic name for such a method?
Other possible names could be: "construct", "constructor", "set_up", "init", "__init__" (an ode to Python), "ITFO", etc.
What is most commonly seen? Is there an ideal name?
2. Is there an idiomatic name for the class instance as the first parameter?
I've seen both "self" and "this" used commonly:
method setup*(self: Fruit) {.base.} =
and
method setup*(this: Fruit) {.base.} =
I've got no preference (being both a Python and Javascript coder, I'm used to both.) I'm just asking if there is a general convention of any kind.
3. Are there any pros/cons to returning the instance to enable one-line setup
Changing the above a bit:
'
# from the module:
# ...
method setup*(self: Fruit): Fruit {.base.} =
discard self.setup(42)
return self
# example in use:
var a = Fruit(species: "apple").setup()
echo $a.double_meaning
This works; but I don't see others doing it. Is that because it is non-idiomatic? Because it is slow or fails in odd border cases?
Thanks everyone!
I guess the NEP needs a link to this document: https://nim-lang.org/docs/apis.html
TL;DR: You should define a newFruit procedure which performs the "setup". That answers #1 and #3. (Note that for non-ref object the convention is initFruit)
As for #2, I'm not aware of any idiomatic name. I always name it whatever I wish, if I were to pick something it would be self though.