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 Ba
Besides exceptions being likely, querying a database is a slooooow operation. In both aspects, using property getters as a database accessor violates the principle of least astonishment to client code. If I see a library class with a property, I don't expect it to do a lot of work, but to access a value that's easily retrieved.
The least astonishing option here is to provide an old fashioned, simple Get function.
The Short Version: Making a property getter directly access a database would violate The Separation of Concerns principle.
More Detail:
Generally speaking, a property is intended to represent data associated with an object, such as the FirstName
property of a Person
object. Property values may be set internally or externally, but the act of modifying and retrieving this data on the object should be separated from the act of retrieving or committing that data to a permanent store.
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
A getter, by definition, should just be encapsulating data, not functionality.
Also, you would likely be redefining functionality and making many trips to the database if you had more than one getter that needed to round-trip to the database. Why not handle that in a centralized place rather than splitting that out among multiple properties?
Methods are for class-level data modification and functionality, properties are for individual data modification and retrieval only.
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.
Any time you accessed the getter, you'd be making another call out to your database.