开发者

DDD and Factories

Hi I have a few questions regarding Domain Driven Design and using Factories / Factory Methods. Per the Domain Driven Design Blue Book (Eric EVan's Book) it states that complex constructors should be encapsulated inside Factories / Factory Methods / Builders so there is a consistent place where you check all the invariants, so my question is regarding this:

Let's say I am developing a magic organizer application where you can make CRUD like operations on magic effects (like a post on a blog + several attributes like effect duration, materials used (list of strings), patter associated with the magic effect) and some of the invariants are that a magic effect must always have a title, a content of the magic effect, a duration and an optional patter and must be published by a user registered in the application.

So since I have quite a few invariants I have a EffectBuilder that builds MagicEffect objects and checks all the invariants.

Is it ok to do something like this in the user class?

public class User {
// Several attributes and business methods

public MagicEffect publishEffect(final S开发者_如何学JAVAtring title, final String content, final Long duration, final Collection<String> elements) [
EffectBuilder builder = new EffectBuilder();

builder.withAuthor(this);
builder.withTitle(title);
builder.withContent(content);
builder.withDuration(duration);
builder.withElements(elements);

return builder.build();
}
};

Or should I do something like:

public class User {
// Several attributes and business methods

public EffectBuilder publishEffect() [
EffectBuilder builder = new EffectBuilder();

builder.withAuthor(this);

return builder;
}
};

And somewhere else

User user = userRepository.findById(userId);
MagicEffect effect = user.publishEffect().withTitle(title).withContent(content).withDuration(duration).withElements(elements).build();

userRepository.save(user);

I mean the first example I have a huge method with huge amount of parameters but I make sure all the invariants are set in the effect when it's built, in the other scenario I programatically improve the code readability by having a fluent interface but I canot make sure the invariants are met 100% of the time.

Which is the better approach? Is there a more balanced approach of doing it?

Thanks Pablo


I think that your second approach is better. The whole point of Builder is to avoid large list of parameters like you have in your first example. Builder is not responsible for enforcing invariants in the object that it builds. Object itself enforces them. I think it is perfectly fine to have an instance of EffectBuilder without Title or with a default title. As long as the MagicEffect itself enforces 'Every effect should have a title' invariant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜