An aspect of Nim that’s giving me trouble is ensuring that objects get 
initialized properly. I’ve gotten used to constructors in C++/Swift/TypeScript, 
which enforce that any instance of object type T has been properly initialized. 
Whereas in Nim, as in Go and Objective-C, objects get initialized as all 
zeros/nil and initialization is by convention, using procs like `init(var T)`.

I’m finding bugs in my code where I forget to initialize an object, writing 
`var t = T()` but then forgetting to call `t.init(a,b,c)` afterwards. Is there 
a way to prevent `T()` from being used outside T’s module? IIRC, Nim 2 will 
have an annotation for object fields that requires an explicit initialization 
of that field; is that correct? Is there an experimental pragma for this in 
1.6.x?

In the standard library I see a convention of defining a `newT(...)` proc that 
creates and initializes a T. Unfortunately this doesn’t support subclassing: if 
I define a type `U = object of T`, then to initialize a U I need to first 
initialize it as a T but there’s no separate function for that. Maybe there 
should be both a `newT()` and an `initT()` function, for subclassable types?

Anyway, **I’m wondering if the Nim community has evolved some explicit best 
practices for object initialization.** For instance, in Objective-C the 
universal convention is to have an `init` method, which must first call the 
superclass’s `init` method if it exists; and there can optionally be 
convenience methods that create and initialize an instance in one call.

Reply via email to