重构可能返回返回的函数

时间:2014-06-16 22:04:42

标签: vb.net refactoring return

我正在处理一个非常大的函数中的一些旧代码,我需要编写一个新函数,从旧函数中调用几次。这个新函数将在旧函数的早期提供关于我是否需要Return的信息。

我的问题是什么是更直接或更好的方法来完成下面的内容?我该怎么重构呢?

我想另一种要问的方式是...... Return Return的更好方法是什么?

Public Class ExampleClass

''' <summary>
''' This function calls another function
''' </summary>
''' <returns></returns>
Protected Overridable Function FunctionOne() As Boolean
    FunctionOne = False
    Dim lobjOne, lobjTwo, lobjThree As Object
    Dim lblnExit As Boolean = False
    '
    ' Some logic here (manipulates/gets objects)
    '
    lblnExit = FunctionTwo(lobjOne, lobjTwo)
    If lblnExit Then
        Return lblnExit
    ElseIf lobjOne.This.That > 2 Then
        Return lblnExit
    End If
    '
    ' Some more logic here (manipulates objects)
    '
    lblnExit = FunctionTwo(lobjOne, lobjTwo)
    If lblnExit Then
        Return lblnExit
    ElseIf lobjOne.This.That > 2 Then
        Return lblnExit
    End If
    '
    ' Performing some final actions
    '
End Function


''' <summary>
''' This function is called by FunctionOne Multiple Times
''' </summary>
''' <returns></returns>
Protected Overridable Function FunctionTwo(ByVal pobjOne As Object, ByVal pobjTwo As Object) As Boolean
    FunctionTwo = False
    '
    ' Performing some long complicated checking that either Returns true or exits
    '
End Function

End Class

2 个答案:

答案 0 :(得分:1)

您可以稍微简化条件逻辑。

lblnExit = FunctionTwo(lobjOne, lobjTwo)
If lblnExit Or lobjOne.This.That > 2 Then
    Return lblnExit
End If

答案 1 :(得分:1)

您可以通过将FunctionTwo调用和结果检查封装在lambda表达式中来避免重复的条件逻辑:

Protected Overridable Function FunctionOne() As Boolean
    FunctionOne = False
    Dim lobjOne, lobjTwo, lobjThree As Object
    Dim lblnExit As Boolean = False
    Dim functionTwoEx =
        Function()
            lblnExit = FunctionTwo(lobjOne, lobjTwo)
            Return lblnExit OrElse lobjOne.This.That > 2
        End Function
    '
    ' Some logic here (manipulates/gets objects)
    '
    If functionTwoEx() Then
        Return lblnExit
    End If
    '
    ' Some more logic here (manipulates objects)
    '
    If functionTwoEx() Then
        Return lblnExit
    End If
    '
    ' Performing some final actions
    '
End Function

这是否更好取决于您的实际检查有多复杂,以及您可以设置functionTwoEx名称的意义。