Sorry for the waffly title - if I could come up with a concise title, I wouldn\'t have to ask the question.
Suppose I have an immutable list type. It has an operat
This is probably a stretch, but in Ruby there is a commonly used notation for the distinction: add
doesn't mutate; add!
mutates. If this is an pervasive problem in your project, you could do that too (not necessarily with non-alphabetic characters, but consistently using a notation to indicate mutating/non-mutating methods).
I think this may be one of those rare situations where it's acceptable to overload the +
operator. In math terminology, we know that +
doesn't append something to the end of something else. It always combines two values together and returns a new resulting value.
For example, it's intuitively obvious that when you say
x = 2 + 2;
the resulting value of x is 4, not 22.
Similarly,
var empty = new ImmutableList<string>();
var list1 = empty + "Hello";
var list2 = list1 + "immutable";
var list3 = list2 + "word";
should make clear what each variable is going to hold. It should be clear that list2
is not changed in the last line, but instead that list3
is assigned the result of appending "word" to list2
.
Otherwise, I would just name the function Plus().
Personally, I like .With(). If I was using the object, after reading the documentation or the code comments, it would be clear what it does, and it reads ok in the source code.
object.With("My new item as well");
Or, you add "Along" with it.. :)
object.AlongWith("this new item");
How about mate, mateWith, or coitus, for those who abide. In terms of reproducing mammals are generally considered immutable.
Going to throw Union out there too. Borrowed from SQL.
list.CopyWith(element)
As does Smalltalk :)
And also list.copyWithout(element)
that removes all occurrences of an element, which is most useful when used as list.copyWithout(null)
to remove unset elements.
Whenever I'm in a jam with nomenclature, I hit up the interwebs.
thesaurus.com returns this for "add":
Definition: adjoin, increase; make further comment
Synonyms: affix, annex, ante, append, augment, beef up, boost, build up, charge up, continue, cue in, figure in, flesh out, heat up, hike, hike up, hitch on, hook on, hook up with, include, jack up, jazz up, join together, pad, parlay, piggyback, plug into, pour it on, reply, run up, say further, slap on, snowball, soup up, speed up, spike, step up, supplement, sweeten, tack on, tag
I like the sound of Adjoin
, or more simply Join
. That is what you're doing, right? The method could also apply to joining other ImmutableList<>
's.