mercredi 13 juillet 2022

Generic builder for populating properties pattern

I created a builder class to populate properties in my models for testing scenarios

    public partial class ModelBuilder
    {
        private Model myModel;
        public ModelBuilder CreateNew(int id)
        {
            myModel = new Model(id);
            return this;
        }

        public ModelBuilder WithName(string name)
        {
            myModel.Name = name;
            return this;
        }

        public ModelBuilder WithAge(int age)
        {
            myModel.Age = age;
            return this;
        }

        public ModelBuilder WithComplexLogic(int data)
        {
            myModel.ProcesData(data)
            return this;
        }

        public Model Build()
        {
            return myModel;
        }
    }

I can use it like this

var modelBuilder = new ModelBuilder<Model>();
modelBuilder.WithName("Name");
modelBuilder.WithAge(30);
modelBuilder.WithComplexLogic(42);
var model = modelBuilder.Build();

Is it possible to create a more generic version for this so I can use it for other classes without creating new methods for setting simple properties values? I was thinking something with lambda syntax for Name and Age, but ComplexLogic() stays the same.

var modelBuilder = new ModelBuilder<Model>();
modelBuilder.WithProperty(x => x.Name = "Name");
modelBuilder.WithProperty(x => x.Age = 30);
modelBuilder.WithComplexLogic(42);
var model= modelBuilder.Build();





Aucun commentaire:

Enregistrer un commentaire