Refactoring method with many conditional return statements

I have a validation method 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 always best 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.

+3
source share
4 answers

, . , , , - , . , "" - , if . , , :

, , ? ? ? , "" , ?

+11

:

return (Check1 == false)   ||   (Check2 == false)   [ || etc ]
+1

, , , ... , - :

For Each ctrl As Control In Me.Controls

    Dim check As CheckBox = TryCast(ctrl, CheckBox)

    If check IsNot Nothing AndAlso check.Checked = False Then
        Return False
    End If

Next

Return True

: , psuedocode, . , , . , (IRule ) , true/false, .

+1

, - :

        bool isValid = true;
        isValid &= Condition1;
        isValid &= Condition2;
        isValid &= Condition3;
        if (!isValid)
            return false;

, if. , , , "if" .

, , . ( , ), , , .

This is true, however, if all conditions are consistent. If they are distributed throughout the code, with significant processing between checks, the metric indicates real complexity (more branches that need to be tested). In this case, you might be wondering if the method can be logically broken down into smaller, individually verifiable fragments.

0
source

Source: https://habr.com/ru/post/1735112/


All Articles