Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should a C# property getter not read from a DB?

Tags:

c#

properties

Some of the answers and comments to this question: Simplest C# code to poll a property?, imply that retrieving data from a database in a property's getter is Generally a Bad Idea.
Why is it so bad?

(If you have sources for your information, please mention them.)


I will usually be storing the information in a variable after the first "get" for reuse, if that influences your answer.

like image 328
Protector one Avatar asked Jul 13 '11 17:07

Protector one


2 Answers

Because retrieving data from a database could cause any number of exceptions, and property getters, as a rule, should never throw exceptions.

The expected behavior of a property getter is just to return a value; if it's actually doing a lot more than that, it should be a method.

Microsoft's guide for Property Design explains the reasons: https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/property

like image 154
Flynn1179 Avatar answered Sep 21 '22 05:09

Flynn1179


It's bad because (among other things) it violates the Principle of Least Astonishment.

Programmers generally expect properties to do simple gets/sets. Encapsulating data access in a property, which could throw exceptions, cause side effects, and change the state of the data in the database, is not what is generally expected.

I'm not saying there is no case for complex properties - sometimes, it can be a good solution. But, it is not the expected way to do things.

like image 20
womp Avatar answered Sep 19 '22 05:09

womp