0

What's the preferred way to handle the following case:

switch (numberOfActualBytes)
{
    case 1: return something1;
    case 2: return something2;
    case 3: return something3;
    case 4: return something4;
}

I know for certain that numberOfActualBytes due to the used contract is in range 1-4.

How should I write the code that doesn't result in not all code paths return a value error?


I suspect I should throw some exception at the end of this function or in default switch case, but probably there is a better solution.

Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148

3 Answers3

8

I prefer to throw an out-of-range exception in the default case if the application can be expected to uphold the 1..4 contract. The exception reflects the expectation on the caller that they will give me good data.

If your compiler cannot figure out that the default case solves the not all code paths, then put the return after the switch. But the c# compiler will get it right.

drdwilcox
  • 3,833
  • 17
  • 19
0

default: return error_code would be my solution.

smitec
  • 3,049
  • 1
  • 16
  • 12
0

I would probably do something like this.

declare temp_something = a default value; //Used to check for error.

switch (numberOfActualBytes)
{
    case 1: temp_something = something1; break;
    case 2: temp_something = something2; break;
    case 3: temp_something = something3; break;
    case 4: temp_something = something4; break;
}
return temp_something;

Wouldn't this do the same?

Ajai
  • 3,440
  • 5
  • 28
  • 41
  • Sure, but it obscures the fact that anything but 1-4 is a violation of the semantics of the function. – drdwilcox Nov 24 '11 at 04:08
  • Hhhhmm. In that case if the outofrange exception should be checked then an if structure before the switch would reduce the overhead of going through the switch. `if(!((0 < numberOfActualBytes) && (numberOfActualBytes <4))) { //Throw an exception;}else //go to switch;` – Ajai Nov 24 '11 at 04:15
  • Not at all. Doing so obscures the switch statement, imo. The simple `default: throw exception;` says the same with much less code. – drdwilcox Nov 24 '11 at 04:26