Avoid Exposing Collections Directly as Properties
page 3 of 6
by Steven Smith
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 28677/ 30

Guarding Against Destructive Actions

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:


View Entire Article

User Comments

Title: Picture links all broken (404)   
Name: Anonymous
Date: 2012-12-12 8:46:55 AM
Comment:
The images are blank and result in a 404 if opened individually.
Title: Very nice   
Name: Thanigainathan
Date: 2011-03-28 2:36:03 PM
Comment:
Hi,

The article is very nice. So you mean only the parent of the list property can modify its state. Will this be sort of restricting the features of collections ?

Thanks,
Thani






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 1:20:32 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search