Is it okay to violate the principle that collection properties should be readonly for performance?
I used FxCop to analyze some code I had written. I had exposed a collection via a s开发者_StackOverflow中文版etter. I understand why this is not good. Changing the backing store when I don't expect it is a very bad idea. Here is my problem though. I retrieve a list of business objects from a Data Access Object. I then need to add that collection to another business class and I was doing it with the setter method. The reason I did this was that it is going to be faster to make an assignment than to insert hundreds of thousands of objects one at a time to the collection again via another addElement method.
Is it okay to have a getter for a collection in some scenarios? I though of rather having a constructor which takes a collection? I thought maybe I could pass the object in to the Dao and let the Dao populate it directly? Are there any other better ideas?
If the properties aren't part of your public API, knock yourself out; otherwise no. But then, are you actually sure that this is a performance bottleneck? I'd wager you're prematurely optimizing at this point.
I would still make the property read only, and provide an alternative method that takes a collection and does the assignment — possibly the constructor. Sure, that's a what a property setter is supposed to be for, but this makes it really clear to a class user that you don't expect this property to moved out from under you, and assignment should only happen in exceptional circumstances.
精彩评论