Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what does it mean Define the Normal Flow in clean code book?

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?
thank you in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 incapulated 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 realisation.

This approach will let you modify your software in an easy way and follows the OCP and SRP.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading