On 12/01/2013 09:57 PM, CJS wrote:

> I was reading the enum page of Ali Çehreli's (excellent) D book
> (http://ddili.org/ders/d.en/enum.html), and I'm confused by an enum
> value (not enum type), such as
>     enum secondsPerDay = 60 * 60 * 24;
> In that situation I would have used an immutable variable. Is there any
> reason to prefer enum vs. immutable when defining constants?

After realizing the other day that even 'static const' can be used for template instantiations, I am not sure myself anymore. :)

Simple rules are great. I wanted to accept the following guidelines, none of which are clear cut:

1) Prefer enum first because enum values can be used for template instantiations.

2) Prefer immutable next because it provides stronger guarantees.

3) Prefer const last as it erases immutable attribute if present. (We can't know just by looking at a reference to const whether the original value has been immutable or mutable.)

The first item needs qualification: Do not use enum for arrays and associative arrays, because enum is like copy+pasting the definition everywhere the enum is used. It is expensive to initialize arrays and AAs.

The second item needs qualification: immutable is not just a stronger const, it is a requirement, a burden. It requires that the object is deeply immutable and it is also a burden on types: They cannot contain mutable references. (This affects future development; you can't add mutable references to a type that has already been used as immutable somewhere in the code.)

So, it is not a clear cut decision because it depends on the type as well. For example, these days I use const even for manifest constants like 60 * 60 * 24 because for all practical purposes it is a manifest constant! This must be new in D; I don't think it worked that way but it works even with CTFE now. Additionally const is shorter to type and easier on the eyes. :)

Ali

Reply via email to