Skip to content

Instantly share code, notes, and snippets.

@asarnaout
Last active October 2, 2018 22:27
Show Gist options
  • Save asarnaout/d3ffdc6ba7a4c27f6f3bd423f84d801c to your computer and use it in GitHub Desktop.
Save asarnaout/d3ffdc6ba7a4c27f6f3bd423f84d801c to your computer and use it in GitHub Desktop.
public class Customer // PRE REFACTORING
{
public decimal EarnedRewards { get; private set; }
public int TotalPoints { get; private set; }
public DateTime MemberSince { get; private set; }
public void CalculateRewards()
{
var pointLimit = 5000;
if (EarnedRewards > 50)
pointLimit = 10000;
if (TotalPoints > pointLimit)
{
var rewardValue = 5m;
if (DateTime.UtcNow.Year - MemberSince.Year >= 5)
rewardValue *= 2;
TotalPoints = TotalPoints - pointLimit; //Side Effect!
EarnedRewards = rewardValue; //Side Effect!
}
}
}
public class Rewards //Refactoring to an immutable Value Object
{
public decimal EarnedRewards { get; }
public int Points { get; }
public Rewards(decimal earnedRewards, int points)
{
EarnedRewards = earnedRewards;
Points = points;
}
public Rewards Earn(Rewards other)
{
if (other == default(Rewards))
return this;
return new Rewards(EarnedRewards + other.EarnedRewards,
other.Points);
}
public Rewards RedeemPoints(int memberShipYears)
{
var pointLimit = 5000;
if (EarnedRewards > 50)
pointLimit = 10000;
if (Points < pointLimit)
return default(Rewards);
var rewardValue = 5m;
if (memberShipYears >= 5)
rewardValue *= 2;
return new Rewards(rewardValue, Points - pointLimit);
}
}
public class Customer
{
public Rewards Rewards { get; private set; }
public DateTime MemberSince { get; }
public int MemberShipYears => DateTime.UtcNow.Year - MemberSince.Year;
public void AdjustRewards()
{
Rewards = Rewards.Earn(Rewards.RedeemPoints(MemberShipYears)); //Declarative Style
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment