www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: const?? When and why? This is ugly!

Derek Parnell Wrote:

 On Sat, 07 Mar 2009 17:08:58 -0500, Burton Radons wrote:
 Am I going to become a broken record on this? Because
 "invariant (char) []" is the string type, data that
 is going to be mutable will always find its way into
 that type in order to deal with an API which WILL use
 string as its arguments, not writing out
 "const (char) []". 

I'm starting to think that 'string' for function parameters should be a rare thing. For a function to insist that it only recieves immutable data sounds like the function is worried that it might accidently change data. And that sounds like a bug to me. It is shifting the responsibility to the caller for the data's integrity.
 It gives me no information about
 the future of the object while removing the apparent
 need for the gentleman's agreement. Therefore I have
 no way of knowing what the actual pedigree of this
 string I've been given has. It may be invariant, it
 may be mutable.

But why would your function care about that? Let's assume your function's signature is 'const' for its parameters because it does not intend to modify any of them. If the caller passes invariant data then your function cannot modify the arguments. If the caller passes mutable data, the compiler won't allow your function to modify the parameters either, due to the const signature. So why is it important that the function should know the mutability of the passed data?

In my example the function's signature is like this: int cachedComputation (string x) { static int [string] array; return array [x] = hugeComputation (x); } According to the strict interpretation of the standard I should be able to say that the contents of x will never be modified or destroyed, but because it's the default that's used everywhere in Phobos that forces everything to be casted to string before it can be used anywhere, I can't assume it has more weight than const.
Mar 07 2009