What's the best name for a non-mutating “add” method on an immutable collection?

前端 未结 30 1259
夕颜
夕颜 2020-11-29 16:47

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

30条回答
  •  暖寄归人
    2020-11-29 17:25

    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();
    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().

提交回复
热议问题