I asked a question on StackOverflow regarding how to 'best' use the Builder pattern for constructing a Value Object which could be constructed with or without optional parameters.

One answer stated that:

A builder is not part of the domain driven design paradigm because it cannot be expressed as part of your domain's ubiquitous language

Whilst Domain Driven Design suggests the use of a Factory for complex object creation, I didn't think it excluded other patterns.

Is this suggesting that a Builder does not belong in the domain layer? I did not think Domain Driven Design cared about technical implementation such as choice of patterns.

有帮助吗?

解决方案

After looking at your other question I don't believe you are talking about the gang of fours builder pattern. I think you're talking about Josh Bloch's builder pattern.

It lets you write code like this:

NutritionFacts cocaCola = new NutritionFacts
    .Builder(240, 8)
    .calories(100)
    .sodium(35)
    .carbohydrate(27)
    .build()
;

The point here is to simulate named parameters in languages that don't have them natively. This allows the creation of an immutable value object with many fields without having to resort to setters or long unreadable constructors. Since the need for this is highly language dependent it really has nothing to do with anything Domain Driven Design talks about. If it did then certain languages couldn't be used for DDD. I think DDD would be fine with this so long as you use good names. So no, I don't think DDD prohibits use of builders.

Keep in mind, factory, builder, or new this is construction code. It shouldn't be casually mixed with your behavioral code.

And of course you can use factories with builders to separate the concrete implementation from the more abstract formula.

Nutrition secretFormula(Nutrition nutrition) {
    return nutrition
        .Builder(240, 8)
        .calories(100)
        .sodium(35)
        .carbohydrate(27)
        .build()
    ;
}

Nutrition dietFormula(Nutrition nutrition) {
    return nutrition
        .Builder(240, 8)
        .calories(0)
        .sodium(40)
        .carbohydrate(0)
        .build()
    ;
}

I think this shows that the ubiquitous language can be made manifest in builders. Your domain expert should be able to read this just fine.

其他提示

I don't think that DDD and the builder pattern are mutually exclusive, however the builder is just a utility to help construct the domain model.

If your Domain object and your Builder are separate classes, then:

  • The domain object is part is part of your domain model
  • The builder is not--it's just a utility class that helps construct your domain model

If they are in the same class, then the lines are blurred a bit. To be pedantic, the builder portion of the class is not domain specific. The properties and methods on the constructed domain model are.

To be honest the distinction is mostly academic and not worth arguing over.

许可以下: CC-BY-SA归因
scroll top