Search code examples
javaexceptionrefactoring

Normal Flow expression in clean code book of Robert C Martin?


I am reading clean code which is written by Robert C. Martin in the 7 section about error handling There is a piece of code that I could not understand it.

    try {
     MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
     m_total += expenses.getTotal();
    } catch(MealExpensesNotFound e) {
     m_total += getMealPerDiem();
    }

what does it mean? and it is written that we need to refactor it via special case pattern like the following:

    public class PerDiemMealExpenses implements MealExpenses {
     public int getTotal() {
     // return the per diem default
     }
    }

Can you translate it in a simple way for me?


Solution

  • Exceptions make the logic of a method confusing and hard to maintain, and they also cause bugs. Please take a look at the code you've provided: it throws a MealExpensesNotFound if there are no expenses. Following this approach, you will probably need to handle other exceptions if the expenses are less than some threshold or, for example, negative. To fix this, Robert Martin suggests using the Special Case pattern.

    Instead of raising exceptions, the expenseReportDAO.getMeals will always return the MealExpense object. All you need to do is to incapsulate the logic for your particular case in a separate PerDiemMealExpenses class. PerDiemMealExpenses.getTotal() contains a default logic in this example. Following this approach, if you need to handle another case, you add another class for that.

    The trick is that now the decision of choosing the right behaviour is incapsulated in the expenseReportDAO.getMeals(employee.getID()) call. The client's code will stay the same without modifications needed to support additional cases:

    MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
    m_total += expenses.getTotal();
    

    If the meals are not expensed, the PerDiemMealExpenses will be returned, with its custom implementation.

    This approach will allow you to easily modify your software and conforms to OCP and SRP.