Last active
May 22, 2017 19:52
-
-
Save Youenn-Bouglouan/8fb6d69f7224ba6d155b8380c1b7113f to your computer and use it in GitHub Desktop.
How to efficiently break your code by using exceptions? Example 1: Pokemon exception catching
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; | |
namespace FunWithExceptions | |
{ | |
/* | |
* 'Vindigator' is an imaginary 3rd-party library that contains | |
* a lot of useful (if you're into the vindication business) APIs. | |
*/ | |
public static class Vindigator | |
{ | |
/// <summary> | |
/// Return true if the customer is a good customer, false otherwise. | |
/// </summary> | |
public static bool IsCustomerAGoodCustomer(Customer customer) | |
{ | |
if (customer == null) | |
throw new VindigatorInvalidCustomerException("Something is wrong with your customer!"); | |
if (customer.AmountOwed < 1000) | |
return true; | |
return false; | |
} | |
} | |
public class VindigatorInvalidCustomerException : Exception | |
{ | |
public VindigatorInvalidCustomerException(string message) : base(message) | |
{} | |
} | |
public class Customer | |
{ | |
public int Id { get; set; } | |
public string Code { get; set; } | |
public Decimal AmountOwed { get; set; } | |
} | |
public class VindicationReport | |
{ | |
public Customer Customer { get; set; } | |
public bool IsGoodCustomer { get; set; } | |
public Decimal MoneyOwed { get; set; } | |
} | |
public class ValuationRates | |
{ | |
public Decimal PercentageFee { get; set; } | |
public DateTime ValuationDate { get; set; } | |
} | |
public static class MyBusinessApp | |
{ | |
public static VindicationReport GenerateVindicationReport(Customer customer, ValuationRates rates) | |
{ | |
var report = new VindicationReport { Customer = customer }; | |
try | |
{ | |
report.IsGoodCustomer = Vindigator.IsCustomerAGoodCustomer(report.Customer); | |
if (report.IsGoodCustomer) | |
report.MoneyOwed = report.Customer.AmountOwed; | |
else | |
report.MoneyOwed = report.Customer.AmountOwed + report.Customer.AmountOwed * rates.PercentageFee; | |
} | |
catch (Exception) | |
{ | |
// [Richard] if we get an exception here, it means the customer is null! | |
// Seems to happen when the main vindication job gets stuck (damn John!). Return a null report in that case. | |
return null; | |
} | |
return report; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment