Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Money
- {
- public decimal Amount { get; private set; } // privatni setter, vrednost se postavlja samo u konstruktoru
- public string Currency { get; private set; } // privatni setter
- public Money(decimal amount, string currency)
- {
- // Self-validating: Validacija pri konstrukciji
- if (amount < 0)
- {
- throw new ArgumentException("Amount must be positive.");
- }
- if (string.IsNullOrWhiteSpace(currency))
- {
- throw new ArgumentException("Currency cannot be null or empty.");
- }
- Amount = amount;
- Currency = currency;
- }
- // Behavior-rich i Immutable: Vraća novi objekat, ne menja postojeći
- public Money Add(Money other)
- {
- if (!IsSameCurrency(other))
- {
- throw new InvalidOperationException("Cannot add money of different currencies.");
- }
- return new Money(Amount + other.Amount, Currency);
- }
- // Behavior-rich i Immutable: Vraća novi objekat, ne menja postojeći
- public Money Subtract(Money other)
- {
- if (!IsSameCurrency(other))
- {
- throw new InvalidOperationException("Cannot subtract money of different currencies.");
- }
- // Možda dodatna validacija da rezultat ne ide u minus ako je to poslovno pravilo
- return new Money(Amount - other.Amount, Currency);
- }
- private bool IsSameCurrency(Money other)
- {
- return Currency.Equals(other.Currency, StringComparison.OrdinalIgnoreCase);
- }
- // Jednakost po vrednostima: Override Equals i GetHashCode metode
- public override bool Equals(object obj)
- {
- if (obj == null || GetType() != obj.GetType())
- {
- return false;
- }
- Money other = (Money)obj;
- return Amount == other.Amount && Currency.Equals(other.Currency, StringComparison.OrdinalIgnoreCase);
- }
- public override int GetHashCode()
- {
- return HashCode.Combine(Amount, Currency.ToUpperInvariant());
- }
- // Moguće i predefinisanje operatora za jednakost i nejednakost
- public static bool operator ==(Money a, Money b)
- {
- if (ReferenceEquals(a, null))
- {
- return ReferenceEquals(b, null);
- }
- return a.Equals(b);
- }
- public static bool operator !=(Money a, Money b)
- {
- return !(a == b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement