Is FxCop's CollectionPropertiesShouldBeReadOnly rule incompatible with the spring framework?

℡╲_俬逩灬. 提交于 2020-01-02 10:05:26

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/206746/is-fxcops-collectionpropertiesshouldbereadonly-rule-incompatible-with-the-sprin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!