The current implementation would allow a user of Customer to
set its OrderHistory field to null. This test shows the problem:
![](/ArticleFiles/2046/image002.jpg)
The simplest fix to this is to change our OrderHistory to
use a property, and to make it readonly by giving it a private setter. With
this change in place, the above test no longer even compiles, so we should be
safe from this problem.
![](/ArticleFiles/2046/image003.jpg)
However, users of the system can still perform destructive
actions on the OrderHistory by using the List<Order> type's methods. For
instance, they can Clear() the collection, as this next test shows:
![](/ArticleFiles/2046/image004.jpg)
In order to remove access to the List<T> class's
methods, we can hide the implementation details of our internal representation
behind a read-only interface, like IEnumerable. However, changing to
IEnumerable also means we can no longer add directly to OrderHistory - this is
also a good thing, since that was exposing too much internal state. Thus we
add a method to Customer specifically for adding orders to the order history.
The resulting class and tests are shown below:
![](/ArticleFiles/2046/image005.jpg)
![](/ArticleFiles/2046/image006.jpg)