2

Here's the code that I have:

int getPos(string partOfSpeech)
{
    var pos = 0;
    switch (partOfSpeech)
    {
        case "noun":
            pos = 1;
            break;
        case "verb":
            pos = 2;
            break;
        case "adjective":
            pos = 3;
            break;
        case "Adverb":
            pos = 4;
            break;
        default:
            pos = 5;
            break;
    }
    return pos;
}

I would like to simplify this if possible. Is it a valid (and sensible) thing for me to just do a return from inside the switch?

Saadi
  • 2,211
  • 4
  • 21
  • 50
  • 5
    Yes...................... – Rotem Jun 01 '16 at 12:52
  • 1
    yes it is valid just write return "whatever" – Abdul Rehman Sayed Jun 01 '16 at 12:52
  • Why not? It's just a question of what you like better. – Drew Kennedy Jun 01 '16 at 12:52
  • It is usually more readable and easier to debug to only have a single return within a method. However nothing will stop you from putting multiple returns in, and there can be reasons why to have multiple return statements instead of just one. – Adwaenyth Jun 01 '16 at 12:55
  • 1
    I would try to not get into the habit of using a switch statement as they are a really good way of breaking SO from the SOLID principles – Callum Linington Jun 01 '16 at 12:55
  • 2
    @Adwaenyth I disagree, it's easier to debug when you have multiple returns, otherwise you need to keep track of some variable that you are returning which could change multiple times. – Jamie Rees Jun 01 '16 at 12:56
  • 2
    @JamieR multiple exit points in a complex method make it rather difficult to assert when you have clean up operations to do like rolling back changes or something like that. It is easier to read (and faster) when you have single (or few) line instructions though. – Adwaenyth Jun 01 '16 at 12:58
  • I don't know if C# works the same as VB, but in VB you can assign the name of the function a value and that value will be returned at the end. (i.e. `pos = 2` -> `getPos = 2`) This would allow for a little shorter code, not declaring a placeholder variable, and you wouldn't have to have return statements in the switch statment. – вʀaᴎᴅᴏƞ вєнᴎєƞ Jun 01 '16 at 13:35

5 Answers5

4

Yes

int getPos(string partOfSpeech)
{
    switch (partOfSpeech)
    {
        case "noun":
            return 1;
        case "verb":
            return 2;
        case "adjective":
            return 3;
        case "Adverb":
            return 4;
        default:
            return 5;
    }
}

I think this code may be interesting too (In a line).

int getPos(string partOfSpeech)
{
    return partOfSpeech == "noun" ? 1 : partOfSpeech == "verb" ? 2 : partOfSpeech == "adjective" ? 3 : partOfSpeech == "Adverb" ? 4 : 5;
}

Or maybe you can declare an enum and use it like this:

enum partOfSpeech
{
    noun = 1,
    verb = 2,
    adjective = 3,
    Adverb = 4
}

You can pass enum:

int getPos(partOfSpeech p)
{
    return (int)p;
}

Or string:

int getPos(string p)
{
    partOfSpeech pos;
    Enum.TryParse(p, out pos);
    return (int)pos == 0 ? 5 : (int)pos;
}
MSL
  • 990
  • 1
  • 12
  • 28
2

Technically yes, you can use return statement instead of break. Although this is a simple solution, imagine whether this would be a smart decision in the long run maintenance-wise.

Why would you want to have five returns instead of one? It looks much cleaner to have one exit point from the function then five. Also, it would be confusing for someone looking at you code to figure where the method exits, etc. If you really want to simplify the above method, you might want to rewrite it completely in order to decrease the cyclomatic complexity of your method. So, something like this could be valid:

// Probably somewhere at the beginning of the class as a private global field
private Dictionary<string, int> _partOfSpeechDict;
public yourClassConstructor()
{
    _partOfSpeechDict = new Dictionar<string, int>();
    _partOfSpeechDict.Add("noun", 1);
    _partOfSpeechDict.Add("verb", 2);
    _partOfSpeechDict.Add("adjective", 3);
    _partOfSpeechDict.Add("adverb", 4);
}

int getPos(string partOfSpeech)
{
    var pos = 5; // For 'other' or default in your case

    if (_partOfSpeechDict.ContainsKey(partOfSpeech)) 
    {
        pos = _partOfSpeechDict[partOfSpeech];
    }
    return pos;
}
Huske
  • 9,186
  • 2
  • 36
  • 53
1

To clarify, what return does:

return (C# Reference):

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

So return will return to the calling method and it doesn't matter where it is used. It also works in a switch statement i.e. in place of a break command.

Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
0

The statement list of a switch section (i.e., case block) typically ends in break, goto case, or goto default. However, any construct that renders the end point of the switch section unreachable is permitted. The following is valid:

switch (id)
{  
    case 1:
        // Some processing
        throw new ArgumentException();
    case 2:         
        // Some processing
        return;
    case 3:
        // Some processing
        goto case 4;
    case 4:
        // Some processing
        goto default;
    default:
        // Some processing
        break;
}
Y Diranieh
  • 11
  • 1
-1

There is a requirement (enforced by the compiler) that all cases definitely end. The usual way is to end it on a break (as in you sample), but other possibilities exist, such as:

  • goto - explicitly jump to another case
  • throw an exception
  • and return

So yes, it is possible to return from the function from within a case block.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • 2
    You could say the requirement is that the end of the `case` section _is not reachable_. For example this is valid: `case "noun": while (true) { } case "verb": ...`. So you do not need `break`/`goto`/`throw`/`return`/`continue`/etc as such, but that is clearly the most usual thing. – Jeppe Stig Nielsen Jun 01 '16 at 13:15