On this page
What a module is
In 1972, David Parnas published a short paper on how to split a system into modules. For him, a module was a responsibility assignment: a part of the work that one person or group owns. Such a module can hold many functions.
Every module has two sides. The public contract is the small set of types and methods that other code may use. The internal details are everything else, including the data that the module stores. The boundary is the line between the two.
Figure 1 shows two modules in one app. Code in Orders may call the Billing contract. It may not use an internal Billing class, and it may not read the Billing tables.
What a boundary costs
A boundary makes some changes cheap and others expensive. You pay for it in four ways:
- Every call goes through the contract, even when a handy class sits right on the other side. Parnas also noted that many calls across modules can make a program slower.
- Data gets copied. A module hands out its own small types, so you write code that maps its data to them.
- The contract is hard to change. Once other modules call a method, you must update every caller or keep the old version for a while.
- There is more to test: each module through its contract, and the code that maps data in and out.
The size of the cost depends on how strong the boundary is. The table below compares three places to draw the line in .NET. In the last column, a transaction is a group of changes that a database saves together, or not at all.
| Where the line is | What enforces it | A call across it | One transaction across it |
|---|---|---|---|
| A folder or namespace | Nothing. Any code in the same project can use internal types. | A method call | Yes, with one database |
| A separate project | The compiler. Internal types are hidden from other projects. | A method call | Yes, with one database |
| A separate service | The network. Other code can only send messages. | A network message, such as an HTTP request | No |
Across services, you lose this guarantee. Microsoft's .NET architecture guide (opens in a new tab) says you then need eventual consistency: each service saves its own part, and the data agrees again later. The guide calls this much harder to build than a query that joins tables.
Hide the decisions that may change
In his paper, Parnas split one small program in two ways. The program built a KWIC index (key word in context). It made every circular shift of every line, then sorted them. A circular shift moves the first word of a line to the end.
The first design followed the steps of the program: input, shift, sort and output. All its modules shared one format for the stored lines. If that format changed, every module would have to change.
The second design gave each hard decision to one module. Only one module knew how the lines were stored. The others asked it for words and characters through functions, so the same change would touch only one module. Parnas said to begin with a list of the hard design decisions and the decisions that are likely to change. His rule:
Each module is then designed to hide such a decision from the others.
David Parnas, 1972
The paper calls this idea information hiding. Ask what each module hides. A good answer names one decision, such as a file format or the rules for a price. A module that hides nothing has all the costs above and no benefit.
Five questions that help
These questions help you test a line before you draw it.
Does this code change together?
Some parts almost always change at the same time, for the same reason. A boundary between them adds work and saves little. Parnas called the goal product flexibility: a large change inside one module should not force changes in the others. A boundary is in a good place when most changes stay on one side of it.
Who owns this data?
Each table or file should have one owner that writes to it. Other modules ask the owner through its contract. Microsoft's guide sets this rule for services, and it works the same way inside one app. If two modules write to the same table, every change to that table needs both of them. In practice, they are one module with a line through the middle.
The compiler hides types, not tables. When the modules share one database, keeping other modules out of a module's tables is a rule that you must enforce yourself, for example with a separate schema for each module and database permissions, or with a separate database for each module.
Must it be saved in one transaction?
In his book Domain-Driven Design, Eric Evans groups objects into aggregates. An aggregate is a group of objects that is treated as one unit, with one root object that enforces its rules. Evans uses the same boundaries for transactions. Rules inside an aggregate are checked right away. Updates across aggregates happen later, in a separate step.
Apply the same test to modules. If two pieces of data must always be saved in one transaction, keep them in one module. If they can agree a moment later, a boundary can work.
Does each word keep one meaning?
Evans also defines the bounded context: a boundary, often a subsystem or the work of one team, inside which one model applies. A model is the set of ideas and rules that the code uses to describe the business. Inside one bounded context, each term has one meaning.
Microsoft's guide shows one person as a user, a buyer, a payer or a customer, depending on the context. Each context keeps only the details it needs. When one word starts to mean two things in your code, you have probably found a boundary.
Can one team understand it alone?
In 1968, Melvin Conway argued that an organization that designs a system will copy its own communication structure into the design. This is now called Conway's law. Parnas named a related goal: separate groups should be able to work on separate modules with little need to talk. Check that one team can understand and change the module without learning the rest of the system.
A module in C#
In .NET, the strongest boundary inside one app is a separate project. Each project builds its own assembly, the .dll or .exe file that the compiler makes. The internal keyword (opens in a new tab) means that only code in the same assembly can use a type. A class declared directly in a namespace is internal by default, so it stays hidden until you mark it public.
The Billing module below is a class library project, which is a project that builds a .dll file for other projects to use. Its three public types are the interface IBilling, the record Invoice and the small class BillingModule that creates the module. Everything else is internal. To try it, run dotnet new classlib -o Billing, replace Class1.cs with Billing.cs, and save app.cs next to the Billing folder. The template turns on implicit usings, which Billing.cs relies on.
namespace Billing;
// The public contract. Other projects can use only these three types.
public interface IBilling
{
Invoice CreateInvoice(string orderId, decimal amount);
IReadOnlyList<Invoice> InvoicesFor(string orderId);
}
// The data that leaves the module: a separate copy with read-only (init-only) properties.
public sealed record Invoice(string Number, string OrderId, decimal Amount);
// The one way in. The caller never sees the class behind the interface.
public static class BillingModule
{
public static IBilling Create() => new BillingService(new InvoiceStore());
}
// Everything below is internal. Only code in this project can use it.
internal sealed class BillingService(InvoiceStore store) : IBilling
{
public Invoice CreateInvoice(string orderId, decimal amount)
{
ArgumentException.ThrowIfNullOrWhiteSpace(orderId);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
return ToContract(store.Add(orderId, amount));
}
public IReadOnlyList<Invoice> InvoicesFor(string orderId) =>
store.Rows.Where(r => r.OrderId == orderId).Select(ToContract).ToList();
private static Invoice ToContract(InvoiceRow row) =>
new(row.Number, row.OrderId, row.Amount);
}
// How invoices are stored and numbered can change later, so it stays hidden.
// This demo store lives in memory. It is not safe for calls from many threads.
internal sealed class InvoiceStore
{
private readonly List<InvoiceRow> rows = [];
public IEnumerable<InvoiceRow> Rows => rows;
public InvoiceRow Add(string orderId, decimal amount)
{
var row = new InvoiceRow
{
Number = $"INV-{rows.Count + 1:D4}",
OrderId = orderId,
Amount = amount,
};
rows.Add(row);
return row;
}
}
internal sealed class InvoiceRow
{
public required string Number { get; init; }
public required string OrderId { get; init; }
public required decimal Amount { get; init; }
}BillingService and InvoiceStore never leave the project. Callers get Invoice records. Each one is a new copy with read-only properties, so changing it cannot change the stored rows. The way invoices are stored and numbered can change without any change to a caller, and that is the decision this module hides.
The app below is a .NET 10 file-based app (opens in a new tab), a program in one .cs file with no project file of its own. Its first line, #:project, adds a reference to the Billing project. After that, it uses only the contract.
#:project Billing/Billing.csproj
using System.Globalization;
using Billing;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // the same output on every machine
// The app gets the module through its public contract only.
IBilling billing = BillingModule.Create();
billing.CreateInvoice("order-17", 40.00m);
billing.CreateInvoice("order-17", 12.50m);
billing.CreateInvoice("order-18", 5.00m);
foreach (Invoice invoice in billing.InvoicesFor("order-17"))
{
Console.WriteLine(invoice);
}Run it with dotnet run app.cs. It prints the two invoices for order-17:
Invoice { Number = INV-0001, OrderId = order-17, Amount = 40.00 }
Invoice { Number = INV-0002, OrderId = order-17, Amount = 12.50 }Now try to reach past the contract:
#:project Billing/Billing.csproj
using Billing;
// This file reaches past the contract, into an internal type.
var store = new InvoiceStore();It does not build. With the .NET 10 SDK, dotnet run blocked.cs stops with this error:
blocked.cs(5,17): error CS0122: 'InvoiceStore' is inaccessible due to its protection level
The build failed. Fix the build errors and run again.Assembly.GetExportedTypes() lists the public types of an assembly. For Billing, it returns only three: Billing.BillingModule, Billing.IBilling and Billing.Invoice.
At compile time there is one exception. The InternalsVisibleTo attribute makes internal types visible to an assembly that you name, such as a test project. At run time, reflection can still reach internal code. Treat internal as a design boundary. It does not protect against code that uses reflection.
Start with modules in one process
You might want each module to be a separate service from the first day. Martin Fowler wrote about this choice in his 2015 article "Monolith First". A monolith is an app that runs and is released as one program. Microservices split an app into small services that each run in their own process. Fowler saw that almost all the successful microservice stories started with a monolith that got too big and was broken up.
One of his reasons is about boundaries. They are hard to get right at the start. Moving code between services is also much harder than moving it inside one program. He describes one route: build the monolith with clear modules, both in its public interfaces and in how the data is stored. People often call this a modular monolith. In .NET, one way to build it is to make each module a separate project with a contract, internal details and its own tables.
A bounded context can be a separate service or a boundary in the code inside one app, as Microsoft's guide notes. So you can draw the line now and decide later how to run it. If a module later needs its own deployment, it already has a contract and its own data.
Read more
- On the Criteria To Be Used in Decomposing Systems into Modules (opens in a new tab), by David L. Parnas, Communications of the ACM, December 1972
- How Do Committees Invent? (opens in a new tab), by Melvin E. Conway, Datamation, April 1968
- Domain-Driven Design Reference (opens in a new tab), by Eric Evans, a free summary of the patterns in his book
- Monolith First (opens in a new tab), by Martin Fowler, 2015
- Data sovereignty per microservice (opens in a new tab) on Microsoft Learn
- Identifying domain-model boundaries for each microservice (opens in a new tab) on Microsoft Learn
- Access modifiers (opens in a new tab) in the C# guide on Microsoft Learn
Was this post helpful?