This commit is contained in:
Oli Sturm
2026-04-21 14:43:06 +01:00
commit 3e9f0b56c9
11 changed files with 258 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
namespace CsharpOop.Domain;
/// Domain entity / aggregate root representing a bank account
public sealed class Account : AggregateRoot<AccountId>
{
public Money Balance { get; private set; }
// Often present to satisfy serializers / ORMs.
private Account()
{
Balance = new Money(0);
}
public Account(AccountId id, Money openingBalance)
{
if (openingBalance.Amount < 0)
throw new ArgumentOutOfRangeException(nameof(openingBalance));
Id = id;
Balance = openingBalance;
}
// Domain behaviour attached to the entity.
public void Withdraw(Money amount)
{
if (amount.Amount <= 0)
throw new InvalidOperationException("Withdrawal amount must be positive.");
if (Balance.Amount - amount.Amount < 0)
throw new InvalidOperationException("Balance cannot go below zero.");
Balance = Balance.Subtract(amount);
}
}
+4
View File
@@ -0,0 +1,4 @@
namespace CsharpOop.Domain;
/// Value object used to wrap the aggregate identity
public sealed record AccountId(Guid Value);
+7
View File
@@ -0,0 +1,7 @@
namespace CsharpOop.Domain;
/// Conventional DDD base type for aggregates
public abstract class AggregateRoot<TId>
{
public TId Id { get; protected set; } = default!;
}
+8
View File
@@ -0,0 +1,8 @@
namespace CsharpOop.Domain;
/// Repository abstraction used to load and save accounts
public interface IAccountRepository
{
Account? GetById(AccountId id);
void Save(Account account);
}
+33
View File
@@ -0,0 +1,33 @@
namespace CsharpOop.Domain;
/// Value object used to represent money and enforce simple invariants.
/// Note that this implementation uses immutable patterns for the data
/// by returning a new instance for each modification. This is an early
/// recommendation for DDD with OO, but not necessarily the common practice
/// in many real-world implementations.
public sealed class Money
{
// Potentially with a setter - see note above
public decimal Amount { get; }
public Money(decimal amount)
{
Amount = amount;
}
// In many existing DDD/OO codebases you may actually see the use
// of mutable value types.
//
// public void Add(Money other)
// {
// this.Amount += other.Amount;
// }
// On the other hand, sometimes these helpers may be left out
// and operations encoded directly "from the outside":
// newBalance = new Money(oldBalance.Amount - charge.Amount)
//
public Money Add(Money other) => new(Amount + other.Amount);
public Money Subtract(Money other) => new(Amount - other.Amount);
}