The question of a for
within another creates a very high complexity. More in kids, a great mental load to be able to understand what the method should do.
You can use some techniques described in the Uncle Bob Clean Code book (the title is bigger but looking for "clean code" you will find it, the author is Robert C. Martin).
Basically, it suggests that you create a method for every% and and try to be as clear as possible in the method name.
I would go this route:
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 method names and not just something like for
, of course, if you only persist an object in the database then there is no way to write it any other way.
Notice that the way I split the code gets less loaded from understanding every content of salvarObjetosX
, I say this because it's usually not just a method with for
, there are also value assignments, condition checks ...
Where I work we have a goal that each method should have no more than 15 lines, if there is a must have a good reason. We are wandering in being consistent with or flexible with our development rules.