xxxInPlace or xxxCopy?

foobar foo at bar.com
Thu Jan 20 15:03:01 PST 2011


Andrei Alexandrescu Wrote:

> I'm consolidating some routines from std.string into std.array. They are 
> specialized for operating on arrays, and include the likes of insert, 
> remove, replace.
> 
> One question is whether operations should be performed in place or on a 
> copy. For example:
> 
> string s = "Mary has a lil lamb.";
> // Implicit copy
> auto s1 = replace(s, "lil", "li'l");
> assert(s == "Mary has a lil lamb.");
> // Explicit in-place
> replaceInPlace(s, "lil", "li'l");
> assert(s == "Mary has a li'l lamb.");
> 
> So that would make copying the default behavior. Alternatively, we could 
> make in-place the default behavior and ask for the Copy suffix:
> 
> string s = "Mary has a lil lamb.";
> // Explicit copy
> auto s1 = replaceCopy(s, "lil", "li'l");
> assert(s == "Mary has a lil lamb.");
> // Implicit in-place
> replace(s, "lil", "li'l");
> assert(s == "Mary has a li'l lamb.");
> 
> 
> Thoughts?
> 
> Andrei

Like bearophile and others, I too would prefer the default behavior to be the functional option and return a copy by default. As already mentioned this agrees with the immutable d string types.

Regarding the naming scheme we have several options:
1. overload based on immutability. The type system will do the right thing for you but this may be confusing to read, especially if one uses auto frequently.
2. Use past tense a-la python (sort vs. sorted). This reads more naturally for native English speakers but has the same issues as English itself (all those language exceptions such as split). 
3. use "artificial" scheme such as Ruby's bang (sort vs. sort!). This is my preferred option. Benefits are consistency and is easier for for non native English speakers.
Unfortunately, D doesn't allow '!' in function names. "__InPlace" is clear but also verbose. Perhaps we could use some other, more terse, notion? 
something like:
sort vs. sort@ OR sort vs. sort# ?

My two cents...


More information about the Digitalmars-d mailing list