HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Extremely long if-or-or statement just feel wrong

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
statementextremelyjustlongfeelwrong

Problem

I'm sure this is wrong, but I can't think of a cleaner way to do this. I'm looping through a set of column to identify which column identifies the company name, the test is true if one of a large number of tests are true.

if (heading.ToLower().Contains("organisation") ||
            heading.ToLower().Contains("business") ||
            (heading.ToLower().StartsWith("address.") && heading.ToLower().EndsWith(".surname")) || // A and B
            heading.ToLower().Contains("name") && !(nextHeading.ToLower().Contains("organisation") || // A and not any of B
                                                    nextHeading.ToLower().Contains("company") ||
                                                    nextHeading.ToLower().Contains("firm")) ||
 .......This goes on FAR to long (e.g. A == B, but (C != D and E != F)
 { 
      test = true; 
 }


The way I've currently coded it smells wrong (code smell is a bad sign), but using if-elseif-elseif.... feels just as wrong.

Is there a pattern that I'm missing that can simplify this?

Thanks,
Kevin

Solution

Sure. Put this into a function, eg. "isCompanyName". This function can be easily commented and written in separate lines.

if (heading.ToLower().Contains("organisation")
     return true;

 if (heading.ToLower().StartsWith("address.") &&
   heading.ToLower().EndsWith(".surname")))
     return true;


And so on. This allows to comment the separate cases and maybe explain what they are doing. It's also easy to modify. You can also put things like heading.ToLower() in a variable to save space.

Code Snippets

if (heading.ToLower().Contains("organisation")
     return true;

 if (heading.ToLower().StartsWith("address.") &&
   heading.ToLower().EndsWith(".surname")))
     return true;

Context

StackExchange Code Review Q#9550, answer score: 7

Revisions (0)

No revisions yet.