Information Technology Reference
In-Depth Information
Internal state changes mean that it's possible to violate object invariants,
at least temporarily. After you have replaced the City field, you have placed
a1 in an invalid state. The city has changed and no longer matches the state
or ZIP code fields. The code looks harmless enough, but suppose that this
fragment is part of a multithreaded program. Any context switch after the
city changes and before the state changes would leave the potential for
another thread to see an inconsistent view of the data.
Okay, so you think you're not writing a multithreaded program. You can
still get into trouble. Imagine that the ZIP code was invalid and the set
threw an exception. You've made only some of the changes you intended,
and you've left the system in an invalid state. To fix this problem, you
would need to add considerable internal validation code to the address
structure. That validation code would add considerable size and complex-
ity. To fully implement exception safety, you would need to create defensive
copies around any code block in which you change more than one field.
Thread safety would require adding significant thread-synchronization
checks on each property accessor, both sets and gets. All in all, it would be
a significant undertaking—and one that would likely be extended over
time as you add new features.
Instead, if you need Address to be a struct , make it immutable. Start by
changing all instance fields to read-only for outside uses.
public struct Address2
{
// remaining details elided
public string Line1
{
get ;
private set ;
}
public string Line2
{
get ;
private set ;
}
public string City
{
get ;
 
Search WWH ::




Custom Search