Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it true I should not do "long running" things in a property accessor?

And if so, why? and what constitutes "long running"?

Doing magic in a property accessor seems like my prerogative as a class designer. I always thought that is why the designers of C# put those things in there - so I could do what I want.

Of course it's good practice to minimize surprises for users of a class, and so embedding truly long running things - eg, a 10-minute monte carlo analysis - in a method makes sense.

But suppose a prop accessor requires a db read. I already have the db connection open. Would db access code be "acceptable", within the normal expectations, in a property accessor?

like image 601
Cheeso Avatar asked May 19 '09 15:05

Cheeso


2 Answers

Like you mentioned, it's a surprise for the user of the class. People are used to being able to do things like this with properties (contrived example follows:)

foreach (var item in bunchOfItems)
    foreach (var slot in someCollection)
        slot.Value = item.Value;

This looks very natural, but if item.Value actually is hitting the database every time you access it, it would be a minor disaster, and should be written in a fashion equivalent to this:

foreach (var item in bunchOfItems)
{
   var temp = item.Value;
   foreach (var slot in someCollection)
      slot.Value = temp;
}

Please help steer people using your code away from hidden dangers like this, and put slow things in methods so people know that they're slow.

There are some exceptions, of course. Lazy-loading is fine as long as the lazy load isn't going to take some insanely long amount of time, and sometimes making things properties is really useful for reflection- and data-binding-related reasons, so maybe you'll want to bend this rule. But there's not much sense in violating the convention and violating people's expectations without some specific reason for doing so.

like image 72
mqp Avatar answered Oct 21 '22 19:10

mqp


In addition to the good answers already posted, I'll add that the debugger automatically displays the values of properties when you inspect an instance of a class. Do you really want to be debugging your code and have database fetches happening in the debugger every time you inspect your class? Be nice to the future maintainers of your code and don't do that.

Also, this question is extensively discussed in the Framework Design Guidelines; consider picking up a copy.

like image 30
Eric Lippert Avatar answered Oct 21 '22 17:10

Eric Lippert