Possible Duplicate:
Convention question: When do you use a Getter/Setter function rather than using a Property
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?
Edit:
From another article in the MSDN:
The
get
andset
methods are generally no different from other methods. They can perform any program logic, throw exceptions, be overridden, and be declared with any modifiers allowed by the programming language. Note, however, that properties can also be static. If a property is static, there are limitations on what theget
andset
methods can do. See your programming language reference for details.