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

前端 未结 30 1104
夕颜
夕颜 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:35

    I'd go with Cons, for one simple reason: it means exactly what you want it to.

    1. I'm a huge fan of saying exactly what I mean, especially in source code. A newbie will have to look up the definition of Cons only once, but then read and use that a thousand times. I find that, in the long term, it's nicer to work with systems that make the common case easier, even if the up-front cost is a little bit higher.

    2. The fact that it would be "meaningless" to people with no FP experience is actually a big advantage. As you pointed out, all of the other words you found already have some meaning, and that meaning is either slightly different or ambiguous. A new concept should have a new word (or in this case, an old one). I'd rather somebody have to look up the definition of Cons, than to assume incorrectly he knows what Add does.

    3. Other operations borrowed from functional languages often keep their original names, with no apparent catastrophes. I haven't seen any push to come up with synonyms for "map" and "reduce" that sound more familiar to non-FPers, nor do I see any benefit from doing so.

    (Full disclosure: I'm a Lisp programmer, so I already know what Cons means.)

    0 讨论(0)
  • 2020-11-29 17:36

    How about Chain() or Attach()?

    0 讨论(0)
  • 2020-11-29 17:39

    To be as clear as possible, you might want to go with the wordier CopyAndAdd, or something similar.

    0 讨论(0)
  • 2020-11-29 17:39

    DateTime in C# uses Add. So why not use the same name? As long the users of your class understand the class is immutable.

    0 讨论(0)
  • 2020-11-29 17:40

    Added(), Appended()

    I like to use the past tense for operations on immutable objects. It conveys the idea that you aren't changing the original object, and it's easy to recognize when you see it.

    Also, because mutating method names are often present-tense verbs, it applies to most of the immutable-method-name-needed cases you run into. For example an immutable stack has the methods "pushed" and "popped".

    0 讨论(0)
  • 2020-11-29 17:40

    I prefer Plus (and Minus). They are easily understandable and map directly to operations involving well known immutable types (the numbers). 2+2 doesn't change the value of 2, it returns a new, equally immutable, value.

    Some other possibilities:

    Splice()

    Graft()

    Accrete()

    0 讨论(0)
提交回复
热议问题