I'm following a course on Udemy and the teacher said that is a best practice return the update object in an add method. This is the example:
public Recipe addIngredient(Ingredient ingredient) {
ingredient.setRecipe(this);
this.ingredients.add(ingredient);
return this;
}
This method is a method of the class Recipe. In my opinion this is not needed. I think that is more logical to have a void method or maybe return the result of the line:
this.ingredients.add(ingredient); // ingridients is a HashSet
On the other hand with this approach we have the following feature:
tacosRecipe.addIngredient(new Ingredient("Ancho Chili Powder", new BigDecimal(2), tableSpoonUom))
.addIngredient(new Ingredient("Dried Oregano", new BigDecimal(1), teapoonUom));
we can populate the HashSet by calling the method addIngredients
in a row.
What is your opinion? Would you choose clarity (the method doesn't return the update object) or the benefit that gives (calling addIngredients
in a row)?
Edit: someone suggested to me that Better to have 2 methods with clear meaning, or just 1 dual use method? could be an answer to my question. But the question is different. I'm not asking if I should have two method (one get
and one add
). Does make sense have a get
method that return
this
? Is not a singleton then this doesn't make sense to me. The question is: Is it worth the line return this
? The teacher said that do this is a best practice and maybe I missed something.
I want to point out that the goal to do this is not avoid having an output argument (see page 41, Common Monadic Form, last paragraph, book: Clean Code). I'm updating the object of the class itself, a Recipe object. However, it also true that I update an input argument (there is a bidirectional relationship between these two classes). To show that this method not only add an ingredient to the Recipe object, but also update the ingredient I could refactor this method as:
public Ingredient addIngredient(Ingredient ingredient) {
ingredient.setRecipe(this);
this.ingredients.add(ingredient);
return ingredient; // <------ Here the refactoring
}
However I'm not sure that this method is good enough (Is it the Single Responsibility Principle respected?).
So let's simplify this. I suppose for a moment that a bidirectional relationship doesn't exist. In this case I can rewrite the method in a way that we can focus more on my question:
public Recipe addIngredient(Ingredient ingredient) {
this.ingredients.add(ingredient);
return this;
}
Now, does make sense return the object?