Which code is more correct from a design point of view.

Such:

public List<String> getStringList(int expression){ List<String> list; switch(expression){ case 1: list = getList1(); break; case 2: list = getList2(); break; ... } return list; } 

Or this:

 public List<String> getStringList(int expression){ switch(expression){ case 1: return getList1(); case 2: return getList2(); ... } } 

At the moment we do not change or predict that we need to change the list in the getStringList function.

I would like to read a reasonable answer in favor of one or another option.

In the first case, we have one exit point of their function, in switch we only assign the variable that we return, and in the second case, we get several exit points.

  • What is the fundamental difference between these pieces? - Grundy
  • that in the first case we have one exit point of their function, in switch we only assign the variable that we return, and in the second case we get several exit points - Komdosh
  • 6
    The topic itself is hollivarnaya: everyone advises in different ways. - Grundy
  • one
  • 3
    You should not bother with such questions, it’s from the series how to write in for - ...; i++ ...; i++ or ...; ++i ...; ++i . It all depends on the particular case, how convenient it will be, how you like, etc. In books, they often write about some ideal code in a vacuum, yes, I also read several times, for example, that in the method it is necessary that there be 1 return . In practice, there will be a crutch somewhere that takes the code away from ideality and you have to push two or three return . The main thing is that the code is readable, effective, and so that if you need to add a new feature - you can do it without perepilivaya entire project. - iksuy

1 answer 1

In languages ​​with RAII or try / finally, there is no rule by which a single return point from a function is preferable. Therefore, it is necessary to write as it is easier to read, there is no other rule here.

In your case, it seems to me, the introduction of an additional variable serves only the purpose of a single return point in a function, so I would prefer a shorter variant with return from the middle of the switch . The introduction of an additional variable makes the reader remember the result until the end of the switch , and keep it in mind, while the early return allows you to immediately drop this case.

But this, again, is a matter of personal literary preferences. Write how you feel better.