Created
August 19, 2014 12:03
-
-
Save thefringeninja/379f4096ad81ce15e452 to your computer and use it in GitHub Desktop.
Dtos, Value Objects, Casting and You
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DataContract] | |
public class MoneyDto { | |
[DataMember(Order = 1)] public readonly decimal Amount; | |
[DataMember(Order = 2)] public readonly string CurrencyCode; | |
public CurrrencyDto(decimal amount, string currencyCode) { | |
Amount = amount; | |
CurrencyCode = currencyCode; | |
} | |
} | |
[DataContract] | |
public class ConvertMoney : Command { | |
[DataMember(Order = 1)] public MoneyDto MyMoney; | |
[DataMember(Order = 2)] public string ToMoney; | |
public ConvertMoney(MoneyDto myMoney, string toMoney) { | |
MyMoney = myMoney; | |
ToMoney = toMoney; | |
} | |
} | |
public class Money { | |
static readonly IEnumerable<string> CurrencyCodes = ...; | |
private readonly decimal _amount; | |
private readonly string _currencyCode; | |
public Money(decimal amount, string currencyCode) { | |
Guard.AgainstNull(currencyCode, "currencyCode"); | |
Guard.Against<ArgumentException>(false == CurrencyCodes.Contains(currencyCode), "currencyCode"); | |
_amount = amount; | |
_currencyCode = currencyCode; | |
} | |
public Money Convert(string currencyCode, Func<Money, string, decimal> convert) { | |
var result = convert(this, currencyCode); | |
return new Money(result, currencyCode); | |
} | |
public static implicit operator Money(MoneyDto dto) { | |
return new Money(dto.Amount, dto.CurrencyCode); | |
} | |
public static implicit operator MoneyDto(Money money) { | |
return new MoneyDto(money._amount, money._currencyCode); | |
} | |
} | |
void Handle(ConvertMoney command) { | |
Money money = command.MyMoney; | |
var converted = money.Convert(command.ToMoney, this.ConverterService); | |
bus.Publish(...); | |
} | |
// bus.Send(new ConvertMoney(new Money(10, "USD"), "LOL")); // throws because invariants |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment