开发者

Should messaging classes be immutable?

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?


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.

In my eyes once a message is sent there is no reason to change

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜