Information Technology Reference
In-Depth Information
the sender and the possible receivers of notifications. The sender can be
developed completely independently of any receivers. Events are the stan-
dard way to broadcast information about actions that your type has taken.
Item 26: Avoid Returning References to Internal Class Objects
Yo u ' d l i k e t o t h i n k t h a t a r e a d - o n l y p r o p e r t y i s r e a d - o n l y a n d t h a t c a l l e r s
can't modify it. Unfortunately, that's not always the way it works. If you
create a property that returns a reference type, the caller can access any
public member of that object, including those that modify the state of the
property. For example:
public class MyBusinessObject
{
// Read Only property providing access to a
// private data member:
private BindingList < ImportantData > listOfData =
new BindingList < ImportantData >();
public BindingList < ImportantData > Data
{
get { return listOfData; }
}
// other details elided
}
// Access the collection:
BindingList < ImportantData > stuff = bizObj.Data;
// Not intended, but allowed:
stuff.Clear(); // Deletes all data.
Any public client of MyBusinessObject can modify your internal dataset.
Yo u c r e a t e d p r o p e r t i e s t o h i d e y o u r i n t e r n a l d a t a s t r u c t u r e s . Yo u p r o v i d e d
methods to let clients manipulate the data only through known methods,
so your class can manage any changes to internal state. And then a read-
only property opens a gaping hole in your class encapsulation. It's not a
read-write property, where you would consider these issues, but a read-
only property.
We l c o m e t o t h e w o n d e r f u l w o r l d o f r e f e r e n c e - b a s e d s y s t e m s . A n y m e m b e r
that returns a reference type returns a handle to that object. You gave the
 
 
Search WWH ::




Custom Search