This is in addition to the suggestion to use an extension, but applies whether you do or not:
If you have a condition this long, you should isolate it in its own function, for example:
string GetCategory(string input)
{
//all of your conditions
return mySecondString;
}
Then in the method that used to contain this condition you just have the function call instead, like
var category = GetCategory(myString);
This does a few things:
- It makes the method that calls it more readable. Calling the function in a sense acts like a comment. Instead of having all of those conditions and wondering what it's for, they'll see the call to
GetCategory
and understand that you're getting the category. Similarly, when they look at the GetCategory
function itself they'll understand what that code is for from the name of the function that it's in.
- It keeps the calling function shorter. 15 lines or less is a good recommendation. This condition itself is about that size, so separating it ensures that the calling function won't get too long.
Another suggestion - use constants, like
const string AliensVersusBovines = "AVB";
That prevents someone from reading this:
myString.Contains("AVB")
and wondering what "AVB" is, since it's not self-explanatory. If you're going to use that string in multiple classes (which seems likely) then you could create a separate class that just contains all of those constants. That keeps you from having the same string literal scattered throughout your code which can become a maintenance issue.
public class Codes
{
public const string AliensVersusBovines = "AVB";
}
That way your code can read
myString.Contains(Codes.AliensVersusBovines)