The current implementation would allow a user of Customer to
set its OrderHistory field to null. This test shows the problem:
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.
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:
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: