Search Sreeni's Insights

Filter by content type
technical May 14, 2015 7 min read

Introduction to Domain-Driven Design (DDD) - bounded context and ubiquitous language

Domain-Driven Design introduced through ubiquitous language, bounded contexts, glossaries, aggregates, value objects, and business invariants across complex business domains and teams.

Share:

Introduction to Domain-Driven Design (DDD) - bounded context and ubiquitous language

Software can be technically correct and still fail the business because the team has built the wrong model. Developers are calling a thing “account”, operations are calling it “portfolio”, and customers are calling it “fund holding”, while the code is using one vague entity for all three. These naming differences are becoming data and behaviour mistakes as the application grows.

Domain-Driven Design (DDD) gives us a way to model software around the business domain and the language used by domain experts. In this article, we are going to see bounded context and ubiquitous language, and how to apply them without turning every application into a large framework exercise.

TL;DR Summary

  • DDD starts from business problems and domain behaviour, not from database tables.
  • Ubiquitous language is a shared vocabulary used by business and technical people.
  • A bounded context defines where a model and its terms are valid.
  • The same word can have different meanings in different contexts.
  • DDD is most useful where business rules and change are complex.
  • Start with conversations and examples, then model only the distinctions that matter.

Challenges

Language mismatch

When a business user says “customer”, the database may contain an investor, an account holder and a contact. If the team does not clarify the meaning, a feature can read the wrong record while still passing a simple test. The customer experiences this as a business error, not as a modelling issue.

One model for every need

A reporting model needs different information from a trading or publishing model. Forcing all use cases through one giant entity creates many optional fields and unclear rules. The model becomes difficult to change because every team depends on every field.

Technical-first design

Starting with tables often makes the database shape the domain. The team then adds business rules after persistence is already fixed. We should start by understanding decisions and invariants, otherwise the code represents storage instead of the business.

What is Domain-Driven Design?

Domain-Driven Design is an approach for designing software by deeply understanding a domain and expressing its important concepts and rules in the model.

In simple terms, the domain is the problem space in which the business operates. A fund platform has funds, units, valuation dates and subscriptions, a news platform has articles, editors, publication states and topics. DDD asks us to make those meanings explicit in the software.

What is ubiquitous language?

Ubiquitous language is a shared vocabulary used consistently by domain experts, developers, tests and code.

Simply put, if the business says “publish article”, the use case, method name and test should use the same concept. It is not a glossary kept in a document which nobody reads. The language is refined through regular conversations and examples.

What is a bounded context?

A bounded context is an explicit boundary within which a particular domain model and its language have a defined meaning.

In simple terms, “customer” in a sales context may mean a billing account, while “customer” in support may mean a person contacting the help desk. Both are valid in their context. Trying to make one global object satisfy both meanings creates a coupled model.

Why boundaries are important?

Bounded contexts prevent a local rule from becoming a universal assumption. A fund administration context may define a unit valuation, while a reporting context uses a read model prepared for statements. The contexts can exchange identifiers or messages, but they should not silently share every internal concept.

The following diagram depicts bounded contexts connected through explicit translation,

Domain-Driven Design bounded contexts
Domain-Driven Design bounded contexts

Ubiquitous language glossary

Find below a small glossary for two contexts,

TermPricing contextSales context
FundInstrument being valuedProduct being offered to an investor
Unit priceCalculated value for a valuation datePrice shown in a proposal
CustomerNot a primary conceptInvestor or account holder
Valuation dateDate on which price is fixedNot used for the sales workflow

The same word is not always having the same meaning, and this is not a problem when the boundary is explicit. Problems are starting when a Pricing developer is changing the Sales meaning of Fund without talking to Sales experts. We should translate between contexts through a contract or message, rather than sharing one giant object.

Worked aggregate and value object example

Let us take a closer look at a FundUniverse aggregate. The aggregate is protecting the rules for its units, while Money and UnitPrice are value objects,

public sealed class Money
{
    public decimal Amount { get; private set; }
    public string Currency { get; private set; }

    private Money() { }

    public Money(decimal amount, string currency)
    {
        if (amount < 0)
            throw new ArgumentOutOfRangeException("amount");
        if (string.IsNullOrWhiteSpace(currency))
            throw new ArgumentException("Currency is required");
        Amount = amount;
        Currency = currency;
    }
}

public sealed class UnitPrice
{
    public Money Value { get; private set; }
    public DateTime ValuationDate { get; private set; }

    public UnitPrice(Money value, DateTime valuationDate)
    {
        Value = value;
        ValuationDate = valuationDate.Date;
    }
}

The aggregate is owning the invariant,

public sealed class FundUniverse
{
    private readonly List<UnitPrice> prices = new List<UnitPrice>();

    public int Id { get; private set; }
    public string Name { get; private set; }
    public IReadOnlyCollection<UnitPrice> Prices
    {
        get { return prices.AsReadOnly(); }
    }

    public void AddUnitPrice(UnitPrice price)
    {
        if (prices.Any(x => x.ValuationDate == price.ValuationDate))
            throw new InvalidOperationException(
                "A valuation already exists for this date");
        prices.Add(price);
    }
}

The code is not depending on MVC or Entity Framework, hence the rule can be tested quickly. The database mapping is an outer concern. If the rule is placed only in a controller, batch import and Web API can bypass it, and the customer is finding inconsistent unit prices.

Bounded context map

The following map is a simple example,

Pricing Context
  FundUniverse -> UnitPrice -> ValuationDate
          |
          | PublishedPrice contract
          v
Sales Context
  FundProduct -> Investor -> Subscription

Pricing is publishing a PublishedPrice contract, Sales is consuming it and translating the value into its own model. It is not necessary for Sales to know how Pricing calculated the price. In our case, this separation is useful when both teams are changing their workflows independently.

Must Do and Don’ts

  • Must Do: Use the business term in code and tests after the meaning is agreed.
  • Must Do: Keep an aggregate responsible for its invariants.
  • Don’t: share one entity between bounded contexts just to avoid mapping.
  • Don’t: create a value object when the concept has identity and lifecycle.
  • Be mindful: A bounded context can be a module in one application, it does not require a separate service.

When the language mismatch is found only after a wrong price or subscription is reaching the customer, we are taking reactive actions. A proactive team is discussing examples and invariants before coding, then using the agreed language in tests. The trade-off is time spent with domain experts, and in our case it is worth it when the domain rules are changing frequently.

How to find a useful model?

Start with conversations

Talk with domain experts about a real workflow, not only a list of nouns. Ask what can happen, what must not happen, and what changes the state. For a news article, “an editor can publish only after review” is more valuable than a table called Articles.

Capture examples

Use concrete examples to expose ambiguity. “Article is approved” may mean editorial approval, legal approval or publication. Write the example with the business person and ask what the expected result is. This is similar to a pulse check before implementing a rule.

Define terms

Record terms which have one meaning inside the context and challenge terms which are overloaded. If “account” means an investor account in one context and a login account in another, use separate names in code. Clear naming prevents a ripple effect of wrong assumptions.

Identify invariants

An invariant is a rule which must remain true. “A published article must have an approved author” or “a unit transaction cannot use a closed valuation date” are examples. Put the invariant near the model responsible for protecting it, otherwise every caller must remember the rule.

DDD trade-offs

DDD is not needed for a simple lookup screen with little behaviour. A straightforward ASP.NET MVC and Entity Framework application may be clearer with a modest model. For a complex domain with many rules and teams, the conversations and boundaries can provide a competitive advantage by reducing misunderstandings.

Do not create a bounded context only because there are two projects. The boundary must represent a different model, language or ownership. Likewise, do not force microservices from DDD, a bounded context can live as a module inside a monolith and be extracted later.

Wrap up

In this article, we have looked at Domain-Driven Design, ubiquitous language, bounded contexts, a glossary, aggregates, value objects and invariants. I appreciate your time and efforts to read this article. In the next article, I will walk you through CQRS and separating reads from writes.

Related Posts