C#

Lesson 02

Records and immutable DTOs

Use records or init-only properties for response shapes that should not change after mapping.

Good Code

src/ReviewSummary.cs
public sealed record ReviewSummary(
    Guid Id,
    string Title,
    int Score
)
{
    // Record data stays stable after response mapping.
    public bool IsPassing => Score >= 70;
}

Bad Code

ReviewSummary.cs
public sealed class ReviewSummary
{
    public Guid Id { get; set; }
    public string Title { get; set; } = "";
    public int Score { get; set; }

    // Public setters let later code rewrite the response shape.
    public bool IsPassing => Score >= 70;
}

Review Notes

What to review

Good Code

The good version uses a record so the response shape is constructed with all required values and then stays stable.

Bad Code

The bad version exposes public setters for every field. Any later code can rewrite a response after validation, mapping, or logging.

Takeaways

  • DTOs are easier to review when construction and mutation are separate: map once, then pass a stable value.