Information Technology Reference
In-Depth Information
caller a handle to your internal structures, so the caller no longer needs to
go through your object to modify that contained reference.
Clearly, you want to prevent this kind of behavior. You built the interface
to your class, and you want users to follow it. You don't want users to access
or modify the internal state of your objects without your knowledge.
Yo u ' v e g o t f o u r d i f f e r e n t s t r a t e g i e s f o r p r o t e c t i n g y o u r i n t e r n a l d a t a s t r u c -
tures from unintended modifications: value types, immutable types, inter-
faces, and wrappers.
Va l u e t y p e s a r e c o p i e d w h e n c l i e n t s a c c e s s t h e m t h r o u g h a p r o p e r t y. A n y
changes to the copy retrieved by the clients of your class do not affect your
object's internal state. Clients can change the copy as much as necessary to
achieve their purposes. This does not affect your internal state.
Immutable types, such as System.String, are also safe (see Item 20). You
can return strings, or any immutable type, safely knowing that no client of
your class can modify the string. Your internal state is safe.
The third option is to define interfaces that allow clients to access a subset
of your internal member's functionality (see Item 22). When you create
your own classes, you can create sets of interfaces that support subsets of
the functionality of your class. By exposing the functionality through those
interfaces, you minimize the possibility that your internal data changes in
ways you did not intend. Clients can access the internal object through the
interface you supplied, which will not include the full functionality of the
class. Exposing the IEnumerable<T> interface pointer in the List<T> is
one example of this strategy. The Machiavellian programmers out there
can defeat that by guessing the type of the object that implements the
interface and using a cast. But programmers who go to that much work to
create bugs get what they deserve.
There is one strange twist in the BindingList class that may cause some
problems. There isn't a generic version of IBindingList, so you may want
to create two different API methods for accessing the data: one that sup-
ports DataBinding via the IBindingList interface, and one that supports
programming through the ICollection<T>, or similar interface.
public class MyBusinessObject
{
// Read Only property providing access to a
// private data member:
 
Search WWH ::




Custom Search