Refactoring Day 1 : Encapsulate Collection

本文讨论了在某些情况下,为了防止消费者误用集合并引入错误,只暴露可迭代的集合而不提供修改方法的做法。通过一个具体的代码示例展示了如何实现这一点,并提到了.NET框架中其他可用于封装集合的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In certain scenarios it is beneficial to not expose a full collection to consumers of a class. Some of these circumstances is when there is additional logic associated with adding/removing items from a collection. Because of this reason, it is a good idea to only expose the collection as something you can iterate over without modifying the collection. Let’s take a look at some code  
   1: public class Order    2: {    3:     private List<OrderLine> _orderLines;    4:      5:     public IEnumerable<OrderLine> OrderLines    6:     {    7:         get { return _orderLines; }    8:     }    9:     10:     public void AddOrderLine(OrderLine orderLine)   11:     {   12:         _orderTotal += orderLine.Total;   13:         _orderLines.Add(orderLine);   14:     }   15:     16:     public void RemoveOrderLine(OrderLine orderLine)   17:     {   18:         orderLine = _orderLines.Find(o => o == orderLine);   19:         if (orderLine == null) return;   20:     21:         _orderTotal -= orderLine.Total   22:         _orderLines.Remove(orderLine);   23:     }   24: } 
As you can see, we have encapsulated the collection as to not expose the Add/Remove methods to consumers of this class. There is some other types in the .Net framework that will produce different behavior for encapsulating a collection such as ReadOnlyCollection but they do have different caveats with each. This is a very straightforward refactoring and one worth noting. Using this can ensure that consumers do not mis-use your collection and introduce bugs into the code. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值