How often I should be using const? Is it useless/overrated?

XavierAP n3minis-git at yahoo.es
Tue Nov 22 19:23:55 UTC 2022


On Friday, 18 November 2022 at 11:51:42 UTC, thebluepandabear 
wrote:
> A question I have been thinking about whilst using D is how 
> often I should be using const.
>
> Many people claim that all variables should be const by 
> default, but whether or not it is really needed is debatable 
> and oftentimes making everything const could cause readability 
> issues and make the code more complex.
>
> I also wonder how important const really is, like 99% of the 
> time you will know when your variable will be changed, and even 
> when a variable changes it's not like it is the end of the 
> world.
>
> Also, there is no real end to how much variables can be const. 
> Oftentimes -- interestingly -- in popular repos I don't even 
> see const being used, this is what confuses me.
>
> As a newcomer, I'd be interested in hearing everyones thoughts.

IMHO and besides other insights in previous replies, in practice 
this depends on whether you're talking about private 
implementation code, or an external interface -- of a library, 
component/unit (under test), etc.

In private implementation code, including your scripts, informal 
code for personal use etc. you should probably not bother more 
than needed. It's fine that other languages (functional or 
safety-paranoid) force const or immutable by default, it's fine 
that D doesn't. Go with the least verbose default for this kind 
of code.

For external interfaces, be mindful that everything that should 
not be mutated across them, is annotated as const, since 
languages D or C++ provide this facility. Otherwise you'd have to 
rely and unsafely trust on naming conventions like Python.


More information about the Digitalmars-d-learn mailing list