Why use a public property instead of a function to expose a custom collection <T>

During the code review, I looked at a set of repository classes (on vb.net). I'm used to seeing these repository classes full of functions that return collections (among other things) of objects in your domain. However, this repository had 1 public property and 1 private variable, which looked something like this:

Private _item as Collection (of Customer) Public Item as Collection (of Customer) Get... Set... 

In "Get" there is a code that receives Clients from DAL and loads it into a personal _item.

What are the benefits of using a property (customerRepository.Item) instead of the plain old function (customerRepository.GetAllCustomers)? "Property" looks strange to me, but strange doesn't always mean wrong.

+4
source share
3 answers

In this example, the recipient returns the entire collection, and the user is allowed to retrieve items from it. In the repository template, the repository is a collection, and you interact with it with the semantics of the collection to get a specific instance of the object that is supposed to be stored in the repository.

The danger in this implementation is that users of this API may replace the collection with another collection. This is bad practice in my opinion.

+2
source

I agree that performing a setter operation that accesses any type of DAL is bad practice.

According to the MSDN Property Usage Guide, methods should be used when:

  • The operation is expensive enough that you want to tell the user that they should consider caching the result.
  • Retrieving a property value using get accessor will have an observed side effect.

It is so clear that using the property for the above is a violation of this guide.

+3
source

If you mean that in Get (instead of Setter) "there is a code that receives Clients from DAL and loads it in a personal _item", then I saw the code where this is done, but check if there is a private _item. Then it goes into the cache, and it reads only with DAL on first access. Each time he returns directly from the private _item.

Of course, you can also execute the caching script inside GetAllCustomers.

0
source

All Articles