Home > front end >  The builder pattern, delegates and lambda expression- need explanation
The builder pattern, delegates and lambda expression- need explanation

Time:10-15

I am not new in the programming world, however I need help with understanding what is going on in this code. I DO understand the builder pattern and the Action delagete (does not return anything, but can take some parameters).

What bothers me a lot is below code:

    0. var carBuilder = new CarBuilder().WithDoors(x => x.WithDoors(4)).Build();
    1. public CarBuilder WithDoors(Action<DoorsBuilder> x)
    2. {
    3.    var doorsBuilder = new DoorsBuilder();
    4.    x(doorsBuilder);
    5.    _car.AddDoors(doorsBuilder.Build());
    6.    return this;
    7. }
  1. What happens in line 4?
  2. What do I actually pass in line 0 to WithDoors function?
  3. Is is possible to rewrite that code in some simpler way (to get better understanding :))?

Code: https://rextester.com/SIOV54215

CodePudding user response:

What happens in line 4?

At line 4 the code calls the action delegate passing in the DoorBuilder which has been created in line 3, and in line 5 it adds the doors built using the door builder to the car being built by the CarBuilder. This is a fairly common pattern used in composite (or nested) builders. It looks much like a similar answer I gave to a question a number of years ago: Builder pattern with nested objects

What do I actually pass in line 0 to WithDoors function?

Herein is a problem, the naming of your methods is somewhat confusing, both the CarBuilder and the DoorBuilder has a method named WithDoors. I would have made the DoorBuilder have a method named NumberOfDoors making the code more readable, and more obvious what is happening:

var car = new CarBuilder().WithDoors(x => x.NumberOfDoors(4)).Build();

(Note the change of variable name; the result of this line is a (built) car NOT a carBuilder!)

Is is possible to rewrite that code in some simpler way (to get better understanding :))?

I wonder whether there is even a need for a nested builder here, perhaps there is as it becomes more complicated (say, setting the features of the door such as trim, electric wondows, etc etc) but as you have it right now the only thing you can build is the number of doors which could just as easily be put on the CarBuilder itself making the code:

var car = new CarBuilder().WithDoors(4).Build();
  • Related