Builder API for plural properties
For plural properties, it would be great to have Adders in addition to Withers :
Builder for Person:
class Person{
public IEnumrable<Address> Addresses {get;set;}
}
will generate :
WithAddresses (new Address[] { ...}) // **set** addresses
and
AddAddressed (address) // **add** to addresses
RemoveAddressed (address) // **remove** from addresses
I've been thinking about this, and I don't see a way to make it work without fundamentally changing what a builder means. The thing about Builders is that they are just blueprints, and they are still subject to change up until you actually build the object. The factory methods that you (or at least I) build can throw out whatever came before and replace it at any point. The entire collection is meant to be set like any other property. The Add and Remove methods don't actually have a real collection to add or remove from yet, so any items they add and remove would have to be cached to the side somewhere and then added or removed from the collection once it's actually been built. That's not insurmountable, certainly, but it introduces an order of operations that isn't currently there. What if someone replaces the collection after that point? I could just throw out the cache anytime someone replaces the entire property, assuming that they want to start over from that point, but there would still need to be a cache behind the scenes, and it would take at least some of the control away from the test about how things are being done.
I'm still considering things, but can I ask why you would want to set up a builder like this rather than just populating a list, adding and removing things from it, and then setting that as the collection when you're done? It just seems to me that whatever code is creating the Builder would probably have some kind of loop in it anyway. In that case, what's the big difference, other than where the cache collection lives?
See my response on issue #31 (https://github.com/MelGrubb/BuilderGenerator/issues/31#issuecomment-2629501764) I think the non-obvious behavior when you
- add something to a collection
- overwrite that collection
- add some more items
Is reason enough to not touch this. I think the best advice is to prepare the collection the way you want it, and then set the values on the builder. It's just too "squishy" any other way. If anyone has a strategy that would make this predictable to most developers, I'm all ears.