Can anyone suggest some guidance for designing and implementing good Properties? I am concerned with aspects such as:
- Side-effects
- Mutual Exclusivity
- Concurrency
- Symmetry and Reversibility
- Error Handling/Exceptions
Pointers to existing write ups that answer these topics would be great. I am NOT looking for help with WPF Dependency Properties.
As a rule, properties shouldn’t contain almost any logic other than possibly some boundary checks and type checks (depends on language). Thus, every item on the list other than Error Handling / Exceptions should not be factors when implementing properties.
W.R.T Error handling, it is absolutely OK to throw exceptions from properties (i.e. when a calling block attempts to set a property to an invalid value). Also, using try…catch statements are appropriate when attempting to parse data.
An example of this would be in using a property to hide a request parameter in a web application:
this is a bit of a contrived and simplified example, but I hope it illustrates the point. In a real-world application, you might want to have a different method of error handling and/or parsing to check for valid ranges of ID’s and such, all depending upon your circumstances.
The wikipedia entry for properties may also be a good place for more information