現在、DDD における不変式と検証に関する情報を消化しようとしています。私が正しく取得した場合、検証はドメインの問題ではなく、不変条件が発生しないように外部で行う必要があります。一方、ドメイン、特に集合体では、不変条件を適用する必要があります。
私を混乱させるのは、実際には2つのことです。
- ビジネス ルール (不変条件) を検証と区別する方法
- DRY原則を尊重する方法
詳しく説明しましょう。Tendersをカバーする Domain Model があるとします。2 つの主要なアクターは、入札プロセスの主催者 ( Organizer ) と入札プロセスの参加者 ( Participant ) です。主催者は、ステージの条件と要件に関する情報を含む入札公告を発行します (たとえば、最高価格の開始)。入札は、いくつかの段階からなるプロセスです。すべてのステージには条件があります。最初のステージは「入札の募集」です。この段階で、参加者はオファーを送信できます (提案)。
2 つの基本的な要件があります。
- プロポーザル価格は開始上限価格よりも低くする必要があります
- 参加者は、「入札の募集」段階でのみオファーを提出することができます
技術的には、次のように実装できます (詳細は省略します)。
class SubmitHandler
{
/**
* Send proposal
*
* @param SubmitCommand $command
*/
public function execute($command)
{
$this->isReadyToBeSend($command);
$participant = $this->participantRepository->find($command->id);
$participant->submitProposal();
}
private function isReadyToBeSend($command)
{
$result = $this->validate($command);
if (!$result->isValid()) {
throw new ProposalException($result->getMessages()[0]->getMessage());
}
}
public function validate($command)
{
// Here we check if starting price is provided
// and it is less than starting maximum price
// as well as the Call for bids Stage is still active
// so that we are allowed to submit proposals
return Validator::validateForSending($command);
}
public function canBeExecuted($command)
{
return $this->validate($command)->isValid();
}
}
// In the UI we send command to the handler
$commandHandler->handle($submitCommand);
class Participant extends AggregateRoot
{
public function submitProposal()
{
// here we must enforce the invariants
// but the code seems to be almost the same as
// in the validator in the Command Handler
$this->isReadyToBeSent();
}
// throws exceptions if invariants are broken
private function isReadyToBeSent()
{
$this->isPriceCorrect();
$this->AreTermsCorrect();
}
}
上記のすべてを考慮すると、特定のコンテキストでの不変条件と検証の微妙な違いは何ですか? バリデータと集計でコードを複製する必要がありますか? (エンティティにバリデータを挿入したくありません)
どうもありがとうございました。
更新:
私は十分に明確ではなかったと思います。簡単に言うと、次の 2 つの点を考慮する必要があります。
- ビジネス ルールと不変条件の違い。
- SRP に違反する DRY に固執し、その逆も同様です。
最近、私と別の開発者が話し合い、次のような結論に達しました。
- 不変条件は、ビジネス ルールとは別に従わなければならないルールです。概念的には 2 つの異なるものですが、コードは同じかもしれません。
- このコンテキストでの DRY 原則は、SRP 原則に準拠するために違反する可能性があります。
私が間違っている場合は修正してください。