Switch statement with returns — code correctness

前端 未结 17 2218
梦如初夏
梦如初夏 2020-12-12 20:05

Let\'s say I have code in C with approximately this structure:

switch (something)
{
    case 0:
      return \"blah\";
      break;

    case 1:
    case 4:
         


        
17条回答
  •  无人及你
    2020-12-12 20:52

    Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.

    Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.

    One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.

提交回复
热议问题