string is rarely useful as a function argument

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed Dec 28 09:38:35 PST 2011


On 12/28/11 11:42 AM, Peter Alexander wrote:
> On 28/12/11 4:27 PM, Andrei Alexandrescu wrote:
>> The problem is escaping. A function that transitorily operates on a
>> string indeed does not care about the origin of the string, but storing
>> a string inside an object is a completely different deal. The setup
>>
>> class Query
>> {
>> string name;
>> ...
>> }
>>
>> is safe, minimizes data copying, and never causes surprises to anyone
>> ("I set the name of my query and a little later it's all messed up!").
>>
>> So immutable(char)[] is the best choice for a correct string abstraction
>> compared against both char[] and const(char)[]. In fact it's in a way
>> good that const(char)[] takes longer to type, because it also carries
>> larger liabilities.
>
> I don't follow your argument. You've said (paraphrasing) "If a function
> does A then X is best, but if a function does B then Y is best, so Y is
> best."

I'm saying (paraphrasing) "X is modularly bankrupt and unsafe, and Y is 
modular and safe, so Y is best".

> If a function needs to store the string then by all means it should use
> immutable(char)[]. However, this is a much rarer case than functions
> that simply use the string transitorily as you put it.

Rarity is a secondary concern to modularity and safety.

> Again, there are very, very few functions in Phobos that accept a string
> as an argument. The vast majority accept `const(char)[]` or `in char[]`.
> This speaks volumes about how useful the string alias is.

Phobos consists of many functions and few entity types. Application code 
is rife with entity types. I kindly suggest you reconsider your 
position; the current setup is indeed very solid.


Andrei


More information about the Digitalmars-d mailing list