Last active
January 26, 2017 18:26
-
-
Save beyond-code-github/8711794c4d516cb6941d47274884b248 to your computer and use it in GitHub Desktop.
My take on what good, clean C# looks like in the context of http://functionalsoftware.net/fsharp-rewrite-of-a-fully-refactored-csharp-clean-code-example-612/
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
namespace OnlineShop | |
{ | |
delegate decimal Discount(decimal amount, int yearsAccountHeld); | |
public static class Discounts | |
{ | |
public static decimal NotRegistered(decimal amount, int yearsAccountHeld) => amount; | |
public static decimal SimpleCustomer(decimal amount, int yearsAccountHeld) => | |
(amount * 0.9m) * LoyaltyDiscount(yearsAccountHeld); | |
public static decimal ValuableCustomer(decimal amount, int yearsAccountHeld) => | |
(amount * 0.7m) * LoyaltyDiscount(yearsAccountHeld); | |
public static decimal MostValuableCustomer(decimal amount, int yearsAccountHeld) => | |
(amount * 0.5m) * LoyaltyDiscount(yearsAccountHeld); | |
private static decimal LoyaltyDiscount(int yearsAccountHeld) => 1 - (Math.Min(yearsAccountHeld, 5) / 100); | |
} | |
public class DiscountCalculator | |
{ | |
private Dictionary<int, Discount> applyDiscountFor = new Dictionary<int, Discount>() | |
{ | |
{ 0, Discounts.NotRegistered }, | |
{ 1, Discounts.SimpleCustomer }, | |
{ 2, Discounts.ValuableCustomer }, | |
{ 3, Discounts.MostValuableCustomer } | |
}; | |
public decimal Calculate(decimal amount, int accountType, int yearsAccountHeld) => | |
this.applyDiscountFor[accountType](amount, yearsAccountHeld); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The F# (non idiomatic) translation:
Not a vast improvement on the C# but remove most syntactical / keyword cluter
The sum types solution that started this discussion is of course better
For those wondering what's up here
https://www.codeproject.com/articles/1083348/csharp-bad-practices-learn-how-to-make-a-good-code
http://functionalsoftware.net/fsharp-rewrite-of-a-fully-refactored-csharp-clean-code-example-612/
and now this gist and https://twitter.com/beyond_code/status/824367640298844162
😆