📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is primitive obsession? Show how you would fix it in C# with strongly typed IDs, value objects and records, and explain the costs, including EF Core mapping, serialisation and validation.

Explains primitive obsession, the bugs it allows (swapped IDs, unvalidated strings, currency-less money), and how to fix it with readonly record struct IDs, validated value objects and records, including EF Core value converters, JSON serialisation and where to validate.

Mid-Level Coding Intermediate code-quality code-smells primitive-obsession records strongly-typed-ids value-objects

🎯 Key points

  • Primitive obsession: domain concepts (IDs, money, email, ABN) passed as raw Guid, decimal, string
  • Bugs it allows: swapped arguments compile, invalid values flow everywhere, rules duplicated
  • Strongly typed IDs as readonly record struct: zero allocation, value equality, compiler catches swaps
  • Value objects validate once in a factory or constructor; invalid instances can't exist
  • Money as amount plus currency; arithmetic on the type, not on decimals
  • EF Core: ComplexProperty or value converters (HasConversion / ConfigureConventions); JSON: converters or Vogen/StronglyTypedId generators
  • Validate at the boundary, then pass the type inward; don't throw deep inside for user input
  • Costs: mapping code, model binding, a learning curve; use where mix-ups or rules are real

⏱ 30-second answer

Primitive obsession is representing domain concepts with raw types: Guid for every ID, string for email and ABN, decimal for money. The compiler can't tell a customerId from an orderId, so swapped arguments compile, and every caller re-validates (or forgets to).

The fix is small types that carry meaning:

  • Strongly typed IDs: readonly record struct OrderId(Guid Value): no allocation, value equality, swaps become compile errors.
  • Value objects: Email, Abn, Money validate once when created, so an invalid instance can't exist.

The costs are mapping (EF Core value converters or ComplexProperty, JSON converters, model binding) and some ceremony. I use them where mix-ups are likely or rules are real, not for every int.

🗣 Full answer (senior)

How I would answer this in an interview

"Primitive obsession is using built-in types for things that have meaning and rules in the domain. An order ID is a Guid, a customer ID is a Guid, so Refund(Guid orderId, Guid customerId) will happily accept them the wrong way round. An email address is a string, so nothing stops "" or "n/a" reaching the mail sender, and the validation is copy-pasted into every handler. Money is a decimal, so adding AUD to NZD compiles. The smell is the missing type, and the symptoms are duplicated validation, parameter mix-ups and comments like // in cents.

In modern C# the fix is cheap. For IDs I use readonly record struct OrderId(Guid Value): it's a value type, so no allocation, records give value equality and ToString for free, and passing an OrderId where a CustomerId is expected is now a compile error. For concepts with rules I use a value object with a factory, for example Email.Create(string) returning a result or throwing, so validation happens once at the boundary and the rest of the code can trust the type. Money carries amount and currency and implements its own arithmetic and rounding. For example, at [company] we [found a refund applied to the wrong order because two Guids were swapped]; after introducing typed IDs the compiler found [N] more call sites with the same risk.

The mistake I see is going all-in or nothing. These types need plumbing: EF Core value converters or ComplexProperty, JSON converters, route and query binding via IParsable<T>, and Swagger schemas. I use them for IDs that get mixed up, money, and anything with validation rules like ABN or email. A quantity that is just an int with a range check may not be worth a type."


What to replace with what

Primitive Domain concept Better type What it buys you
Guid OrderId, CustomerId readonly record struct Swaps are compile errors
string Email, ABN, postcode Value object with factory Validated once; normalised (trim, lower-case)
decimal Money Money(decimal Amount, Currency Currency) Currency safety, one rounding rule
int + comment Cents, minutes Cents, TimeSpan Units in the type
Several primitives together Address (street, suburb, state, postcode) Record Removes the data clump too

Where each technique fits

Technique Use when Avoid when
Typed ID (record struct) IDs of different entities appear in the same signatures Single-entity microservice with one ID type
Value object (class or record with factory) Rules and normalisation exist No rules, never confused with other values
Source generator (Vogen, StronglyTypedId) Dozens of IDs; want converters generated One or two types: hand-written is clearer

Production example

In an invoicing API with [30] entities, typed IDs typically surface a handful of real swapped-argument bugs at compile time on day one. Moving ABN validation into an Abn value object removes the check from every handler that previously repeated it, and the per-request cost is negligible because record structs don't allocate.

🔍 What the interviewer is checking

Checks that the candidate can turn a smell into concrete C# types and understands the real-world plumbing and costs.

Green flags

  • Gives a concrete bug that primitives allow (swapped Guids, cross-currency maths)
  • Uses readonly record struct for IDs and explains why (no allocation, value equality)
  • Covers EF Core converters or complex types, JSON and binding
  • Validates at the boundary and returns 400s, not deep exceptions
  • Says where not to bother

Red flags

  • Mutable classes with setters as value objects
  • Ignores persistence and serialisation entirely
  • Wants to wrap every int and string

📚 Learn in depth

1. Why primitives leak meaning

A type is a set of allowed values plus allowed operations. string allows any text and every string operation; an email address allows a tiny subset and almost none of those operations. When you use string, every function that receives one must either re-check it or trust that someone upstream did. Value objects move that knowledge into the type system: parse, don't validate.

HTTP JSON "customerEmail": " [email protected] "
        |
        v  boundary: Email.Create(raw) -> validate + normalise once
     Email("[email protected]")
        |
        v  domain + infrastructure trust the type; no more checks

2. record struct versus record class

  • readonly record struct OrderId(Guid Value): value type, 16 bytes, stack or inline, no GC pressure, compiler-generated Equals, GetHashCode, ==, ToString. default(OrderId) is Guid.Empty, so guard against it.
  • sealed record Email: reference type, can enforce invariants through a private constructor and factory (structs always have a public parameterless default).

Rule of thumb: IDs as record structs, validated concepts as sealed records or classes with a private constructor.

3. Plumbing in .NET 10

EF Core. Two options:

  • Value converters: HasConversion(id => id.Value, v => new OrderId(v)), or for every property of a type at once in ConfigureConventions with configurationBuilder.Properties<OrderId>().HaveConversion<OrderIdConverter>(). Single-column values.
  • Complex types (ComplexProperty, EF Core 8+, improved in later versions): multi-column value objects like Money or Address mapped into the owner's table without identity.

Watch out: some LINQ translations on converted properties are limited (e.g. calling methods on .Value inside queries), and key generation for typed keys needs ValueGeneratedOnAdd handling or client-side Guid.CreateVersion7().

System.Text.Json. Write a JsonConverter<OrderId> or let a generator produce one, so the JSON stays "orderId": "3f2..." rather than {"value": ...}.

ASP.NET Core binding. Implement IParsable<OrderId> and minimal APIs and MVC bind route and query values directly: app.MapGet("/orders/{id}", (OrderId id) => ...).

4. Where validation lives

User input should fail with a 400 and a helpful message, not an exception deep in the domain. Two common shapes:

  • TryCreate(string, out Email?) or a Result<Email> at the boundary, mapped to ValidationProblem.
  • FluentValidation on the request DTO, then Email.Create that throws only for programming errors.

5. Costs

  • More types to name and maintain
  • Converters for EF, JSON, binding, OpenAPI
  • Team learning curve; reviews must stop new Guid customerId parameters creeping back

Try it yourself

  1. Change one method signature from (Guid orderId, Guid customerId) to typed IDs and count the compile errors that reveal call sites.
  2. Benchmark (BenchmarkDotNet, [MemoryDiagnoser]) a dictionary lookup keyed by Guid versus OrderId; confirm zero extra allocation.
  3. Map Money with ComplexProperty and inspect the generated table with dotnet ef migrations script.
  4. Implement IParsable<OrderId> and bind it in a minimal API route.

💻 Code

Before and after for an invoice refund: typed IDs, a validated value object and money with currency.

// Before: primitives everywhere
namespace Billing.Before;

public class RefundService(BillingDbContext db)
{
    // Swapping the two Guids compiles; email and amount are unchecked
    public async Task Refund(Guid invoiceId, Guid customerId, decimal amount, string email, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(email) || !email.Contains('@'))
            throw new ArgumentException("Bad email"); // repeated in 6 other handlers
        var invoice = await db.Invoices.SingleAsync(i => i.Id == invoiceId && i.CustomerId == customerId, ct);
        invoice.Refunded += amount; // which currency?
        await db.SaveChangesAsync(ct);
    }
}
// After: types carry meaning and rules
namespace Billing.After;

using System.Diagnostics.CodeAnalysis;

public readonly record struct InvoiceId(Guid Value) : IParsable<InvoiceId>
{
    public static InvoiceId New() => new(Guid.CreateVersion7());
    public static InvoiceId Parse(string s, IFormatProvider? provider) => new(Guid.Parse(s, provider));
    public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out InvoiceId result)
    {
        var ok = Guid.TryParse(s, provider, out var g);
        result = new InvoiceId(g);
        return ok;
    }
}

public readonly record struct CustomerId(Guid Value);

public sealed record Email
{
    public string Value { get; }
    private Email(string value) => Value = value;

    public static bool TryCreate(string? raw, [NotNullWhen(true)] out Email? email)
    {
        var trimmed = raw?.Trim().ToLowerInvariant();
        email = trimmed is { Length: > 3 } && trimmed.IndexOf('@') > 0 ? new Email(trimmed) : null;
        return email is not null;
    }
}

public enum Currency { Aud, Nzd }

public sealed record Money(decimal Amount, Currency Currency)
{
    public static Money operator +(Money a, Money b) =>
        a.Currency == b.Currency
            ? a with { Amount = a.Amount + b.Amount }
            : throw new InvalidOperationException($"Cannot add {a.Currency} to {b.Currency}");
}

public sealed record RefundRequest(InvoiceId Invoice, CustomerId Customer, Money Amount, Email NotifyEmail);
// EF Core: map every typed ID once, and Money as a complex type
protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
    builder.Properties<InvoiceId>().HaveConversion<InvoiceIdConverter>();
    builder.Properties<CustomerId>().HaveConversion<CustomerIdConverter>();
}

protected override void OnModelCreating(ModelBuilder modelBuilder) =>
    modelBuilder.Entity<Invoice>().ComplexProperty(i => i.Refunded);

public sealed class InvoiceIdConverter() : ValueConverter<InvoiceId, Guid>(id => id.Value, v => new InvoiceId(v));
public sealed class CustomerIdConverter() : ValueConverter<CustomerId, Guid>(id => id.Value, v => new CustomerId(v));

⚠ Common mistakes

  • Mistake: Wrapping every primitive in the codebase. Why it is wrong: Converters and ceremony everywhere for no safety gain. Instead: Start with IDs that appear together in signatures, money, and values with validation rules.
  • Mistake: Treating typed IDs and value objects as the same thing. Why it is wrong: They solve different problems. A typed ID only stops mix-ups between identifiers of different entities; it has no rules beyond "not empty". A value object encapsulates domain rules (format, checksum, currency) and must validate on creation. Instead: Use thin immutable record structs for IDs, and immutable sealed records or classes with a validating factory for value objects.
  • Mistake: Using a mutable class with public setters as a value object. Why it is wrong: Invariants can be broken after creation (a validated Email changed to ""), and equality is by reference. Instead: Immutable record or record struct with a validating factory.
  • Mistake: Making a validated value object a struct with a public constructor. Why it is wrong: default and new() bypass validation. Instead: Use a sealed record with a private constructor for validated values; keep structs for IDs.
  • Mistake: Throwing from value object constructors for user input deep in the domain. Why it is wrong: Users get 500s instead of 400s with field errors. Instead: TryCreate/Result at the boundary, mapped to ValidationProblem.
  • Mistake: Forgetting JSON converters. Why it is wrong: The API contract changes to {"value":"..."} and breaks clients. Instead: Add JsonConverters (or a generator) and contract tests.
  • Mistake: Writing LINQ like o.Id.Value == x against converted properties. Why it is wrong: EF Core may fail to translate it. Instead: Compare typed values directly: o.Id == invoiceId.
  • Mistake: Money as decimal with currency in a separate parameter. Why it is wrong: Arithmetic across currencies still compiles. Instead: A Money type whose operators check currency and own rounding.

🏛 Senior insight: trade-offs

The senior view is that primitive obsession is a type-design problem that also fixes a validation-duplication problem: once Abn exists, the eleven-digit checksum lives in one place and the Privacy-relevant fields are easy to find and treat carefully (for example, an Email or TaxFileNumber type can override ToString to redact in logs). That is a real benefit under the Privacy Act 1988 when you need to show where personal information flows. The types also document the domain: a new developer reading Refund(InvoiceId, Money) learns more than from Refund(Guid, decimal).

I decide by context: how many entity types share signatures, how rich the rules are, and how much the domain is expected to grow. A small CRUD service with one ID type gains little; a billing domain with thirty entities and money in several currencies gains a lot. Performance is rarely the issue: a readonly record struct around a Guid is the same 16 bytes with no allocation, so even hot paths are unaffected; validated value objects that are classes add one small allocation each, which only matters in very high-throughput loops and can be measured with BenchmarkDotNet. On a big codebase I introduce them per bounded context, starting where bugs have actually happened, and add an analyser or review checklist so new raw Guid parameters don't creep back.

Option When it fits Cost When not to
Hand-written record struct IDs Up to ~10 ID types A few lines plus converters each Dozens of IDs: boilerplate grows
Source generator (Vogen, StronglyTypedId) Many IDs, want generated EF/JSON converters A dependency and generated code to understand Team unfamiliar with generators, few types
Value object with factory Rules, normalisation, sensitive data Boundary mapping, error handling No rules and no confusion risk
Keep the primitive Local, short-lived values None Values crossing layers or APIs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions mapping typed IDs or Money in EF Core Why: Checks detailed knowledge of value converters, value comparers and translation limits
    How to answer

    A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.

    • Enums as strings: HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.
    • Strongly typed IDs: readonly record struct OrderId(Guid Value) with a ValueConverter<OrderId, Guid>, applied model-wide in ConfigureConventions. The compiler stops you passing a CustomerId where an OrderId belongs.
    • Money has two parts (amount, currency), so it is a complex type, not a converter: converters map one property to one column.

    You need a value comparer when the converted type is mutable (say List<string> stored as JSON), or edits go unnoticed. In LINQ, compare the whole converted value (o.Id == id); o.Id.Value usually doesn't translate. The trade-off: richer domain types versus a few query restrictions.

  2. When: Candidate calls the new types value objects Why: Checks the DDD distinction between entities and value objects and immutability
    How to answer

    An entity has an identity that stays the same while its attributes change: customer #42 is the same customer after moving house. Two entities are equal if their Ids match. A value object has no identity; it is defined by its values, so two Money(100, "AUD") instances are equal. Value objects should be immutable and validate themselves on creation, so an invalid one can never exist.

    In C#, a record or readonly record struct gives value equality for free, but the generated equality compares collections by reference, so a value object holding a list needs ImmutableArray<T> and a SequenceEqual-based Equals. In EF Core 10, complex types (ComplexProperty) are the preferred mapping: value semantics, no hidden key, and now struct, optional and JSON-mapped complex types (including complex collections). Use a value converter for single-value types like EmailAddress. The trade-off: more types, far fewer invalid states.

🛠 Real-world problems: how you handle them

Refund applied to the wrong invoice because two Guids were swapped
Situation
An invoicing API for [a B2B SaaS product] handling [~20,000] invoices a month. A refund endpoint called `RefundService.Refund(Guid invoiceId, Guid customerId, ...)`, and an internal caller passed the IDs in the wrong order.
Signals
A customer reported a refund note on an invoice that wasn't theirs; the audit log showed the refund call succeeded with a customer ID that matched an invoice ID pattern; no exception, because a fallback lookup matched by ID only.
Investigation
Traced the request in Application Insights to the calling handler; found the swapped arguments in a recently merged PR that had passed review. Searched the solution for methods taking two or more `Guid` parameters: [37] of them. Checked the fallback query that had made the swap succeed instead of failing.
Resolution
Immediate: reversed the refund, fixed the call site and removed the ID-only fallback. Real fix: introduced `InvoiceId` and `CustomerId` as `readonly record struct`s with EF Core converters registered in `ConfigureConventions` and JSON converters, rolling out one module at a time. The compiler flagged [4] further call sites with swapped or suspicious arguments.
Prevention
Added a review checklist item and a simple Roslyn analyser rule (or architecture test) that warns on public methods with more than one raw `Guid` parameter in the domain project. Added contract tests to confirm JSON shapes stayed the same. Documented the decision in an ADR.

How to tell it (STAR)

**S:** At [company] a refund was applied to the wrong invoice because a caller passed `customerId` and `invoiceId` in the wrong order; both were `Guid`s, so it compiled. **T:** I owned the fix and wanted to make this class of bug impossible. **A:** After reversing the refund and fixing the call site, I introduced strongly typed IDs as record structs, with EF Core converters registered once and JSON converters so the API contract didn't change. I rolled it out module by module and added an analyser rule against multiple raw Guid parameters. **R:** The compiler found [4] more risky call sites on the first day, and we've had [no] ID mix-up defects since; the change added [no measurable] latency.

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me