J
James A. Fortune
The next question I have about the "Effective C#" books is with regard
to Public variables and Class exposure. It was unsettling enough for
me to learn that Refection could be used to change read-only
variables.
In book 1, pp. 137-138:
[Item 23: Avoid Returning References to Internal Class Objects]
You'd like to think that a read-only property is read-only and that
callers can't modify it. Unfortunately, that's not the way it works.
If you create a property that creates a reference type, the caller can
access any public member of the object.
....
You created properties to hide your internal data structures. You
provided 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.
....
You've got four different strategies for protecting your internal data
structures from unintended modifications: value types, immutable
types, interfaces, and wrappers.
Elsewhere in the book, he seems to promote using immutable types
wherever possible, but what do most programmers do to protect their
internal data structure? Note: I've never written a C# API
personally.
James A. Fortune
(e-mail address removed)
All data members should be private, without exception. -- Bill Wagner
to Public variables and Class exposure. It was unsettling enough for
me to learn that Refection could be used to change read-only
variables.
In book 1, pp. 137-138:
[Item 23: Avoid Returning References to Internal Class Objects]
You'd like to think that a read-only property is read-only and that
callers can't modify it. Unfortunately, that's not the way it works.
If you create a property that creates a reference type, the caller can
access any public member of the object.
....
You created properties to hide your internal data structures. You
provided 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.
....
You've got four different strategies for protecting your internal data
structures from unintended modifications: value types, immutable
types, interfaces, and wrappers.
Elsewhere in the book, he seems to promote using immutable types
wherever possible, but what do most programmers do to protect their
internal data structure? Note: I've never written a C# API
personally.
James A. Fortune
(e-mail address removed)
All data members should be private, without exception. -- Bill Wagner