5

Basically, I was always in the understanding that you should return the expose base types whenever you can and worry about implementation details internally, which makes sense...

But, I'm not sure what to do here. Basically, right now I have:

ReadOnlyObservableCollection<Foo> MyFoos {get; private set; }

I'm wondering if that should be returned as a ReadOnlyCollection<Foo> or an ICollection<Foo> because internally I never really use any observable parts or attempt to write to the collection. WPF seems to not care what I return, it still binds it and triggers the collection changed notification event properly. But, I read somewhere that I should design this to really have any consuming view handle my ViewModel.

So I'm a bit torn here. I'm thinking that leaving it as a ReadOnlyObservableCollection<T> makes the most sense to explicitly tell the consuming view what they can and can not do with the property, but I'm also under the impression that you should reduce down types to their base types when you can. So I'm not sure what to do here. Especially with the fact that WPF doesn't care what type I return, it figures out that it's observable.

michael
  • 14,844
  • 28
  • 89
  • 177
  • 1
    According to Jeffrey Richter, to provide the greatest flexibility to your callers, your arguments should be as base as possible (e.g., IEnumerable instead of List when all you are doing is enumerating the list) and your returns should be as specific as possible (i.e., when you return a List callers can treat it as a List, IList, ICollection, IEnumerable, etc) –  Jul 29 '11 at 15:17
  • Oh, so it's arguments in as minimal as possible, returns as specific as necessary. – michael Jul 29 '11 at 15:32
  • Yeah, that's a decent rule of thumb I try to follow. –  Jul 29 '11 at 15:52

2 Answers2

8

I would probably leave it as ReadOnlyObservableCollection because that very specifically states what a consumer of your ViewModel is allowed to do with your collection. Also note that WPF doesn't actually bind directly to your collection, it binds to the return value of CollectionViewSource.GetDefaultView, which returns an ICollectionView. ICollectionView has INotifyCollectionChanged in its contract.

2

From a performance perspective, you would want to at least use an items source as a collection that implements INotifyCollectionChanged. MVVM provides a lot of benefits but is primarly concerned with unit testing and separation of concerns, so that choice of whether to use a ReadOnlyObservableCollection or an interface like ICollection{T} would be based on your unit testing goals.

Oppositional
  • 11,141
  • 6
  • 50
  • 63