On Wed, 15 May 2013 18:32:03 +0100, Jonathan M Davis <jmdavisp...@gmx.com> wrote:
What's less clear is what to do when a function accepts strings but isn't really operating on them (e.g stuff in std.file or std.net.curl), as they may need immutable(char)[]. In that case, it depends on what's being done with the string. For better or worse though, at this point, I think that it's most common to just accept string for those cases. It's not something that always has a clearcut answer though.

I agree with the first bit, but I think we can make a clear-cut decision on this last..

To me it comes down to a Q of responsibility.

Should a function/method (like those in std.file) require that the argument will not change for the lifetime of the function/method call, or is it reasonable for the function/method to assume the caller will ensure that.

Taking by immutable(char) will guarantee it will not change (ignoring blunt forced cast) whereas const(char) will not, but there is an implicit assumption that it wont change and the caller should guarantee that.

So, who's responsibility is it to ensure the function/method call executes without errors caused by mutable shared data?

I think it's the callers responsibility and think that const(char) is the better choice in cases like this, my reasoning as follows..

1. Callers should already be protecting shared mutable state before using it, this is a common and well understood pattern which cannot be avoided even if we use immutable(char) arguments (caller still needs to ensure shared state is not mutated while they make the immutable copy to pass).

2. In most cases, in most code shared data is less common, especially for calls to functions/methods like those mentioned here. So, we chose the option which is nicer for the common case, and const(char) is it.

3. const(char) does not require duplication of arguments by caller or callee so is more efficient, one of D's primary goals and a good baseline to build upon.

So, I think in cases where the function/method doesn't need to retain the argument for longer than the lifetime of the call it should accept const(char), otherwise as you mentioned earlier it's better to simply require the caller provide the immutable(char) you require.

This decision has a nice side-effect of implicitly documenting the lifetime/usage of arguments, const(char) means call lifetime, immutable(char) means longer, possibly indefinitely (until termination).

Thoughts?

R

--
Using Opera's revolutionary email client: http://www.opera.com/mail/

Reply via email to