Is it correct to just use a public property or should I rather make a private field _count
? I have read some info on the topic, but I can't find an answer.
public int Count
{
get
{
if (this._feeds.IsValueCreated)
{
return this._feeds.Value.Count;
}
else
{
return this._dbConnection.Table<T>().Count();
}
}
}
public FeedRepository(SQLiteConnection dbConnection)
{
this._dbConnection = dbConnection;
this._feeds = new Lazy<IList<T>>(() => _dbConnection.Table<T>().ToList());
}
This is a classic example of where a property really shines.
Properties allow you to encapsulate data, in this instance Count
is actually doing some clever stuff as it's being lazily loaded from a DB on first access and then pulled from a local cache. The beauty of a using a property over a field here is you can bury all this logic behind the accessor, and as far as the consumer is concerned they only need to be aware of the Count
property.
On the other hand, if you used _count
then the consumer would need to understand that they would have to load this value first or it would need to be loaded prematurely in preparation.
So yes, a property is definitely the way to go here.