Search code examples
code-metricscyclomatic-complexitydata-processing

What is the best way to reduce cyclomatic complexity when validating data?


Right now I'm working on a web application that receives a significant amount of data from a database that has a potential to return null results. When going through the cyclomatic complexity for the application a number of functions are weighing in between 10 - 30. For the most part the majority of the functions with the high numbers have a lot of lines similar to the following:

If Not oraData.IsDBNull(4) Then row("Field") = oraData.GetString(4)

Which leads me to my question, what is the best way to go about trying to bring these numbers down? Right now I'm looking at having the majority of the functions below 10.


Solution

  • What about using Extension Methods.

    Imports System.Runtime.CompilerServices
    
    Module Extensions
    
        <Extension()> _
        Public Function TryGetString(ByVal row As IDataRecord, i As Integer) As String
            If row.IsDBNull(i) Then
                Return null
            End If
            Return row.GetString(i);
        End Function
    
    End Module
    

    Then you can simply write:

    row("Field") = oraData.TryGetString(4)
    

    This reads smoothly and reduces cyclomatic complexity on your functions.