Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring method with many conditional return statements

I have a method for validation that has many conditional statements. Basically it goes

If Check1 = false 
  return false
If Check2 = false
  return false
etc

FxCop complains that the cyclomatic complexity is too high. I know that it is not best practice to have return statements in the middle of functions, but at the same time the only alternative I see is an ugly list of If-else statements. What is the best way to approach this?

Thanks in advance.

like image 596
MC. Avatar asked Dec 13 '22 23:12

MC.


1 Answers

I disagree with your claim that it's not best practice to have return statements in the middle of methods. The lengths some people go to in order to have a single return statement is crazy - go with whatever produces the most readable code. Sometimes that will be a single point of return, but often I find there's an "early out" - and it's better to have that return than to introduce more nesting to the code with an if for the alternative path. I like methods that don't end up indented too far, as a rule of thumb :)

Having said that, is the method really nothing but checks? Are the checks independent? What variables do they require? Can you group them into smaller methods representing "areas" of the checks you're performing?

like image 89
Jon Skeet Avatar answered Feb 23 '23 21:02

Jon Skeet