Question

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());
}
Was it helpful?

Solution

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.

OTHER TIPS

If you are using a Smart-UI pattern then there is no problem having logic residing within getters and setters. Sometime our applications are small enough to make this an attractable and easy to use option.

We should keep in mind that the reverse is also true. If it a complex problem we are trying to solve, then we should rethink our domain and how we go about interacting with it. One might argue that putting if statements and other business logic in getters and setters will increase the technical debt in the domain.

an interesting discussion to read is found on programmers: what should be allow inside getters and setters

Hope this helps.

Ps. The smart-ui can also be deemed an anti-pattern depending on the scope of our domain.

This borders on Code Review, but I will try to ask and answer the question you want to ask:

I have a readonly Count property on my Repository pattern. When the repository has been used to load data, the Count property should return the number of records loaded. Otherwise, it should return the Count of all records in the underlying table.

Is the code used in the getter to achieve this considered "too much"?

The answer is: no. The getter does exactly what you expect it to. There are two scenarios, so you need an if. Maybe you can work around it, but it won't make your code any cleaner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top