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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With