D Best Practices: Default initializers for structs

spir denis.spir at gmail.com
Sun Nov 7 04:24:53 PST 2010


On Sat, 6 Nov 2010 21:28:09 -0700
Jonathan M Davis <jmdavisProg at gmx.com> wrote:

> Here's an interesting thought. All built-in types in D default initialize to the 
> closest thing that they have to an error. Floating points arguably do the best 
> job of this with NAN, and integral types arguably the worst with 0, but that is, 
> as I understand it, the basic idea: default initializations initialize to an 
> error value (or as close to one as you can get). That way, it quickly becomes 
> obvious when you failed to properly initialize one before using it. So, the 
> question is this: what about structs?
> 
> Structs default initialize to whatever their member variables are directly 
> initialized to. That may or may not be an error state, but I don't get the 
> impression that people generally _try_ and make it an error state. What should 
> be the best practice on this? Should we generally _try_ and make struct 
> initializers initialize to error states, just like the primitive types do - with 
> the idea that you really are supposed to initialize them or assign to them 
> before you use them. Or should we treat structs differently and try and make 
> their default states something other than an error state?
> 
> By no means am I claiming that we should _always_ try and make a struct's init 
> property an error or _always_ make it valid (that's going to depend on what 
> exactly the struct is for and what it does), but which would be the best 
> practice in the general case?
> 
> - Jonathan M Davis

Very interesting question.
I think that the _general_ rule, as stated above, to make the default value as invalid as possible, does not depend on the complexity of the element's type (say, it's an "orthogonal" point). Thus, what is good for a bool is good for a struct or array. Also note that whether a given type is atomic or not way often depends on the level of the language or of design choices (think at strings). And class instances are null before init.
side-note: the name of the property "init" is a bit misleading, I guess: it's precisely what we find when a var is not yet initialised. I did not get it at once. (But it is correctly named from the compiler/implementation pov.)

Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list