What purpose to const besides functional programming?

Jason House jason.james.house at gmail.com
Wed Jul 23 06:40:15 PDT 2008


Walter Bright Wrote:

> Jason House wrote:
> > What *other* purposes does the const system serve besides
> > opening the door to functional programming?  I understand that the
> > const system must remain simple to be usable.
> 
> 1. It makes function APIs self-documenting.
> 2. Invariance allows one to pass large data structures around by 
> reference yet treat them as if one passed them by value. Strings are the 
> canonical example of that.
> 3. Const allows one function to service both mutable and invariant 
> arguments.
> 4. Invariant data can be placed in hardware protected readonly memory, 
> such as ROM.
> 5. Invariant data does not have to be synchronized to be multithread 
> accessible.
> 6. Invariant data improves the ability of automated tools to make 
> inferences about what is happening. Optimization is an example of such.

#5 is not true.  Invariant functions require synchronization because they can manipulate global state.  If #5 is restricted to direct data access without using properties or member functions, then I'd agree with it.  Of course, that qualification eliminates most of the benefit from #5.

#2 makes me think a bit...  When would const objects be used to manipulate non-const data that isn't effected by transitive const?  It seems to me that simple cases could work, but it quickly breaks down when trying to generalize.
For example, I could write a log utility that writes messages to standard out.  To write to any output, I'd need to store where to write log output to.  Maybe I could circumvent the const system and create a global object that looks up where to write stuff.  That'd let me pass around my logger as an invariant object but then it'd be making an extra function call every time something gets logged.  That's a horrible design.  Advanced compiler tricks may eliminate the overhead, but it doesn't mean it'd save headache for the programmer.  


> > Pure functions requires that any shared data is invariant.
> 
> Yes, but invariant data does not require purity.

I translate that as "I didn't implement it that way".  Also, we need to distinguish between raw access to invariant data and use of (invariant) methods.  See my discussion of your #5 above



> I hope this post will convince you otherwise. If not, I can try again <g>.

And I can try again too :)



More information about the Digitalmars-d mailing list