Using a setter to trigger data updates, best practice
I have an object that is instantiated in the linq to sql method. When the fields of an object are assigned, I want to check the date field and, if it is an old date, extract the data from another table and perform calculations before continuing to assign that object.
Is there something wrong with triggering such an event through the property setter. Or should I check the date myself using some service and make changes if necessary at some point after that?
source to share
There is nothing wrong with doing some kind of logic inside your setters, but you have to be careful how much logic you put into your setters. One of the main problems with setters is that since they act like attributes but have maintenance code, it's easy to forget that there is potentially some non-trivial activity going on behind the scenes.
This kind of thing can cause problems if you have accessors that use access devices that use access devices; you can quickly lead to unexpected performance problems. It is generally a good idea to keep setter actions (or getters for that matter) relatively small in number of actions. For example, validation can work fine in setters, but I usually advised against checking for external resources because of two things: firstly, resource delays can cause problems with the expected access speed, and secondly, the amount of external resources accessing can cause loss of productivity.
Generally, this is the rule: keep it simple. It's not hard to do complex things in setters, but if you do, it is very important to understand the implications of all the actions you will call and it is extremely important to document what does it very well, so the next guy (or girl) to use the code is not just trying to naively use the accessory and end up causing serious resource conflict issues unexpectedly.
source to share
Half the point in using setters instead of, say, public fields is the ability to fire events related to setting specific data.
Keyword: related. If you are just using setter as a "convenient" time to do something else because it works, you are doing it wrong. If setting this value requires other work, then by all means use the installer to do so.
source to share