Good Practices (Refactoring) - Best way to treat one method with for within another

Asked

Viewed 164 times

10

Personal using good Java practice how should I convert this method? I must break into various methods and within each of them do the go?

public void salvarObjetos(Objeto objeto){

   for(Objeto1 obj : container.getList()){
        .
        .
        .
        ObjetoManager.save(obj);
        for(Objeto2 obj2 : obj.getLitObj()){
            .
            .
            .
            Objeto2Manager.save(obj2);
            for(Objeto3 obj3 : obj2.getListObj2()){
                .
                .
                .
                Objeto3Manager.save(obj3);
            }
        }
    }

}

1 answer

10


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 If you liked the answer could you vote? Part of the community indicate good answers or indicate bad answers.

  • I Sorry... had forgotten me. pity I can not yet score with positive point. vlw

  • 1

    Ahhh... yes... I already voted on your question because it helps many people with the same doubt... hehehehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.