消息传递类应该是不可变的吗?
当我说消息传递类时,我指的是严格用于发送并由消费者(或处理程序)使用的类。
我经常看到有关服务总线(例如 NServiceBus)的教程,它们在创建新消息时大量使用自动属性。在我看来,一旦消息发送出去,就没有理由改变。如果消息包含的信息发生任何变化,那么创建新消息并再次发送似乎是公平的。
它们应该是不可变的吗?
When I say messaging classes I mean classes that are used strictly to get sent and be consumed by a consumer (or handler).
Often I see tutorials on service buses (e.g. NServiceBus) that simply make heavy use of automatic properties when creating new messages. In my eyes once a message is sent there is no reason to change. If any changes should occur to the information the message contains then it seems fair to have to create a new message and sent it again.
Should they be immutable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使这些类不可变有很多优点。
消息传递系统往往可以轻松地在传递过程中实现并行或异步。每当引入线程时,不变性都可以提供极大的安全性并防止许多常见错误。
如果这是您的使用场景,那么我肯定会倾向于使用不可变数据类型。就我个人而言,只有在有充分理由需要可变性时才尝试创建可变类型。否则,我总是更喜欢不变性,因为它带来的灵活性以及在改进稍后使用该类型的系统时提供的安全性(即:引入并发性)。
There are many advantages to making these classes immutable.
Messaging systems tend to be something that can easily be made parallel or asynchronous in their delivery. Any time you're introducing threading, immutability can provide a huge level of safety and prevent a lot of common mistakes.
If this is your usage scenario, then I would definitely tend to work with immutable data types. I, personally, try to only make mutable types when there is a valid reason to have mutabililty. Otherwise, I always prefer immutability due to the flexibility it brings and the safety it provides when improving the systems that use the type later (ie: introducing concurrency).
是的,他们应该这样做。正如您所解释的那样,消息在创建后没有理由可以更改。
此外,消息通常用于抽象和/或多线程。如果不使它们不可变,您就会失去不变性提供的好处(例如线程安全)。
Yes, they should. There is no reason a message can be changed after their creation, just as you explained.
Also messages are normally used for abstraction and/or multithreading. By not making them immutable you take away the benefits immutability provides (e.g. thread safety).