In Robert Martin's Clean Code book there is a Java example of when to use the special case pattern. Rather than write this:
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
expenseTotal += expenses.getTotal();
} catch(MealExpensesNotFound e) {
expenseTotal += getMealPerDiem;
}
We'd use:
public class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
// return the per diem default
}
and
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
expenseTotal += expenses.getTotal();
In swift we have nil coalescing so we can skip creating an interface/protocol and go immediately to:
let expenses = expenseReportCalculator.getMeals(employee.id)
expenseTotal += expenses.getTotal() ?? getMealPerDiem
Does this mean the special case pattern is redundant when using Swift? Perhaps I'm either missing the point or there are special circumstances in which this pattern would be valuable.
Aucun commentaire:
Enregistrer un commentaire