What Getters and Setters should and shouldn't do.
- by cyclotis04
I've run into a lot of differing opinions on Getters and Setters lately, so I figured I should make it into it's own question.
A previous question of mine received an immediate comment (later deleted) that stated setters shouldn't have any side effects, and a SetProperty method would be a better choice.
Indeed, this seems to be Microsoft's opinion as well. However, their properties often raise events, such as Resized when a form's Width or Height property is set. OwenP also states "you shouldn't let a property throw exceptions, properties shouldn't have side effects, order shouldn't matter, and properties should return relatively quickly."
Yet Michael Stum states that exceptions should be thrown while validating data within a setter. If your setter doesn't throw an exception, how could you effectively validate data, as so many of the answers to this question suggest?
What about when you need to raise an event, like nearly all of Microsoft's Control's do? Aren't you then at the mercy of whomever subscribed to your event? If their handler performs a massive amount of information, or throws an error itself, what happens to your setter?
Finally, what about lazy loading within the getter? This too could violate the previous guidelines.
What is acceptable to place in a getter or setter, and what should be kept in only accessor methods?