Refactoring Day 1 封装集合

Refactoring Day 1 : Encapsulate Collection 
 
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、付费专栏及课程。

余额充值