The question of a for
within another creates a cyclomatic complexity very high. More in kids, a large mental load to be able to understand what the method should do.
You can use some techniques described in the book "Clean Code" by Bob ( the title is bigger but looking for "clean code" will find, the author is Robert C. Martin ).
Basically it suggests that you create a method for each for
and try to be as clear as possible in the method name.
I’d go this way:
public void salvarObjetos(Objeto objeto) {
for(Objeto1 obj : container.getList()) {
ObjetoManager.save(obj);
salvarObjetos2(obj.getLitObj);
}
}
private void salvarObjetos2(List<Objeto2> obj2List) {
for(Objeto2 obj2 : obj2List){
Objeto2Manager.save(obj2);
salvarObjetos3(obj2.getListObj2());
}
}
private void salvarObjetos3(List<Objeto3> obj3List) {
for(Objeto3 obj3 : obj2.getListObj2()){
Objeto3Manager.save(obj3);
}
}
Remembering that you should try to best describe the names of the methods and not just something like salvarObjetosX
of course if only an object persists in the database then there is no other way to write.
Notice that the way I divided the code is less charged to understand each content of for
, I say this because normally it’s not just a method by for
, there are also value assignments, condition checks...
Where I work we have a goal that each method should not have more than 15 lines, if there is a good reason. We wander to be consistent with or flexible with our development rules.
Show, that’s what I really thought. I already started reading the clean code book. I came across the code of this example in the company that I joined. I asked to be sure to arrive and suggest the changes. thank you very much.
– FernandoLopes
@Fernandolopes If you liked the answer could you vote? Part of the community indicate good answers or indicate bad answers.
– Flávio Granato
I Sorry... had forgotten me. pity I can not yet score with positive point. vlw
– FernandoLopes
Ahhh... yes... I already voted on your question because it helps many people with the same doubt... hehehehe
– Flávio Granato