不可变对象和结构的值对象之间进行选择 [英] Choosing between immutable objects and structs for value objects

查看:127
本文介绍了不可变对象和结构的值对象之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何实现一个值对象(典型的例子是一个地址),作为不可变对象或结构之间进行选择?



是否有表现,语义或任何选择一个比其他的其他好处?


解决方案

你如何实现一个值对象之间进行选择(典型的例子是一个地址),作为不可变对象或结构?




我觉得你的选择是错误的。不可变对象和结构不是对立的,也不是他们的唯一选择。相反,你有四个选项:






    • 可变

    • 一成不变


  • 结构体

    • 可变

    • 一成不变




我认为英寸NET,默认选择应该是一个可变类来表示的逻辑不可变类来表示实体。其实,我倾向于选择不变类甚至逻辑实现,如果在所有可行的。结构应保留小类型的模拟值语义,例如一个自定义的日期类型,复杂号码类型类似的实体。这里要强调的是对的的,因为你不想通过引用大量数据的斑点,并间接复制实际上是便宜(所以我们没有得到利用结构多)。我往往使结构总是的不可变的(我想不出在目前一个例外的)。由于这最适合的内在价值类型的语义我觉得这是一个很好的规则可循。


How do you choose between implementing a value object (the canonical example being an address) as an immutable object or a struct?

Are there performance, semantic or any other benefits of choosing one over the other?

解决方案

How do you choose between implementing a value object (the canonical example being an address) as an immutable object or a struct?

I think your options are wrong. Immutable object and struct are not opposites, nor are they the only options. Rather, you've got four options:

  • Class
    • mutable
    • immutable
  • Struct
    • mutable
    • immutable

I argue that in .NET, the default choice should be a mutable class to represent logic and an immutable class to represent an entity. I actually tend to choose immutable classes even for logic implementations, if at all feasible. Structs should be reserved for small types that emulate value semantics, e.g. a custom Date type, a Complex number type similar entities. The emphasis here is on small since you don't want to copy large blobs of data, and indirection through references is actually cheap (so we don't gain much by using structs). I tend to make structs always immutable (I can't think of a single exception at the moment). Since this best fits the semantics of the intrinsic value types I find it a good rule to follow.

这篇关于不可变对象和结构的值对象之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆