views:

333

answers:

2

FxCop has the CollectionPropertiesShouldBeReadOnly rule that complains if your class has some kind of collection property that clients can set. Instead, it suggests making the property read-only and supplying a Clear() method and Add() or AddRange() methods for changing the contents of the collection.

I agree that makes for a cleaner and more controlled interface, but I'm struggling to make that interface work with the Spring framework. If I want to configure an object with a collection of collaborators, I have to expose some collection property to inject the collaborators into. I've looked through the Spring documentation, and I can't see any way to tell Spring to call the AddRange() method, am I missing something?

For now, I'm going to exclude the warning with a note that it's necessary for Spring configuration.

Update: since I didn't get any nibbles here in the last two months, I posted the same question on the FxCop forum.

+2  A: 

Is the problem as bad as you think? My understanding is that FxCop will complain if you have a read/write property like this:

public List<Foo> Items { get; set; }

... because users of your class would then be able to do this:

myInstance.Items = new List<Foo>();

Obviously you don't want users of your class to completely reassign the list. FxCop therefore recommends this pattern:

private List<Foo> _items = new List<Foo>();
public List<Foo> Items { get { return _items; } }

So now users of your class can only Add and Remove items from your list, rather than overwriting it with a new instance of List.

How does Spring.NET implement its collection properties? Are they really read/write like my first example? If so, it'd be interesting to see their use-cases for such a pattern, because it doesn't seem right.

Matt Hamilton
Spring is a dependency-injection framework, so it's calling myInstance.Items = ... at object creation time. It feels weird, but I think classes designed for use within a dependency-injection / inversion-of-control framework need to be more passive than usual.
Don Kirkby
It sounds like that particular FxCop rule may indeed be "incompatible" with Spring.NET then, unfortunately.
Matt Hamilton
+3  A: 

Hi,

If the collection property only has a getter exposed, we will assume the FxCop recommended patterns you list is used and add to the collection. The first pattern is also supported.

For generic collections this is only working if the exposed property is of the type IList. We have a JIRA issue for the next release to fix this. BTW, this is a very common pattern in the base class libraries (as you probably know...) which is where we first encountered the need to support this style in .NET 1.1 (which doesn't suffer from the limitation listed above).

Cheers, Mark