Refactoring Day 30 : Return ASAP
This topic actually came up during the Remove Arrowhead Antipattern refactoring. The refactoring introduces this as a side effect to remove the arrowhead. To eliminate the arrowhead you return as soon as possible.
1: public class Order
2: {
3: public Customer Customer { get; private set; }
4:
5: public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
6: {
7: Customer = customer;
8: decimal orderTotal = 0m;
9:
10: if (products.Count() > 0)
11: {
12: orderTotal = products.Sum(p => p.Price);
13: if (discounts > 0)
14: {
15: orderTotal -= discounts;
16: }
17: }
18:
19: return orderTotal;
20: }
21: }
</div> </div>
The idea is that as soon as you know what needs to be done and you have all the required information, you should exit the method as soon as possible and not continue along.
1: public class Order
2: {
3: public Customer Customer { get; private set; }
4:
5: public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
6: {
7: if (products.Count() == 0)
8: return 0;
9:
10: Customer = customer;
11: decimal orderTotal = products.Sum(p => p.Price);
12:
13: if (discounts == 0)
14: return orderTotal;
15:
16: orderTotal -= discounts;
17:
18: return orderTotal;
19: }
20: }
</div> </div>
This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.