I'm trying to think of a gift card example that I could model using DDD. For example, I have a gift card entity. In my system at some point, a gift card amount is going to need to be reduced or redeemed. Would I use a gift card service object to reduce the amount? The service would include validating the incoming amount and making sure the new amount isn't more than the balance, ect. Or would this live right on my gift card entity as another method and then just pass my updated gift card object to my repository to persist?
public GiftCard
{
public int Id { get; set; }
public double Amount { get; set; }
}
public GifTCardService
{
public void ReduceAmount(GiftCard card, double amount)
{
// Validation checks to make sure amount can be removed.
// Call gift card repository to actually remove amount.
}
}
To start, you probably want the properties to be read-only. This way the Id
and Amount
cannot change just by setting the value.
Next, you will need a way to place transactions against the gift card. These transactions would debit adjust the amount accordingly. Something like this:
class GiftCard
{
public long Id {get; private set;}
public double Amount {get; private set;}
public void Apply(Transaction tx)
{
if(tx.Amount > Amount)
{
handle insufficient funds
}
else
{
Amount -= tx.Amount;
//other logic if necessary
}
}
}
Keep in mind this is just one of many design options.