views:

50

answers:

2

I used FxCop to analyze some code I had written. I had exposed a collection via a setter. 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?

A: 
Joel Coehoorn
That is why I suggested the constructor possibility as an alternative. Also it communicates my expectations that there should be a collection and it doesn't destroy unit testing. But is it a hack? Could I be do something cleverer or is this okay?
uriDium
+1  A: 

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.

Will
It is close to 1 million elements. I haven't actually measured the difference in performance. It just felt really wrong to be getting all the objects into a list in the Dao, pass the list on, and then iterate through the list and add it to another object. It is double the work.
uriDium
@uri you might have something there. You could, however, pass a reference to the list to the constructor of the other object and expose the same list. Or provide a collection-like facade which actually exposes one to many internally held collections... Lots of different ways to do this without copying them all. It just depends on your requirements and your design.
Will