Last active
October 2, 2018 22:27
-
-
Save asarnaout/d3ffdc6ba7a4c27f6f3bd423f84d801c to your computer and use it in GitHub Desktop.
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
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! | |
} | |
} | |
} |
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
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); | |
} | |
} |
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
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