MelGrubb / BuilderGenerator

A source-generator-based implementation of the Builder pattern
https://melgrubb.github.io/BuilderGenerator/
MIT License
36 stars 8 forks source link

Builder API for plural properties #40

Open jvmlet opened 1 year ago

jvmlet commented 1 year ago

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
MelGrubb commented 1 year ago

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?