The motivation for const (the big picture)

Jason House jason.james.house at gmail.com
Sun Jan 6 15:53:07 PST 2008


guslay wrote:

> I would appreciate if Walter or maybe someone who assisted to the D
> conference could enlight me.
> 
> Taking a step back from the syntax/expressiveness debate, I would like to
> understand better where do const/invariant reside in the grand scheme of
> things. Is the current const/invariant the end goal, or does it lead to
> something else?
> 
> Why is const/invariant necessary?

I don't think I match your criteria for someone you want to hear from, but
I'll try anyway ;)

I view const as part of an API specification.  Essentially a contract
promising to not modify the data that is passed into a function (or held by
a class, etc...).

Conceptually, this is useful (like in, out, ref parameters in functions)
because it helps understand the intended functionality and gives a
mechanism for the compiler to catch accidental violations of the intent.

Unfortunately, const (AKA readonly) does not do anything for the compiler
besides giving it extra work to check code.  There's no guarantee that data
won't be changed when calling functions or through actions of another
thread.  Because of this, the compiler can not optimize code under the
assumption that the data never changes.  As I understand it, this is the
purpose of invariant.  I've also heard (but never seen
justification/explanation) that invariant helps with functional
programming.

I share a lot of your questions, and I hope someone who knows more than me
can jump in and explain this stuff better.



More information about the Digitalmars-d mailing list