r/visualbasic • VB Guru • Aug 07 '15

Writing clean code - simplify your code.

I was handed an application recently from a developer who is leaving the company and it contained many oracle functions like the following;

Protected Sub SaveAdjustment_Names(ByVal sadjnameid As String, ByVal sADj_Name As String, ByVal sComments As String, ByVal sEntered_BY As String, ByVal sADJ_STATUS As String, ByVal sACTION As String)
    'TODO:   refactor this
    Try
        Dim sconstr As New AppFunctions
        Dim oracon As New OracleConnection(sconstr.sConstring)
        Dim cmdOra As New OracleCommand
        cmdOra.CommandType = CommandType.StoredProcedure
        cmdOra.CommandText = "WAP.AP_ADJUST_NAME_CHANGE"  '
        cmdOra.Connection = oracon
        Dim pavtid As New OracleParameter
        pavtid.OracleDbType = OracleDbType.Varchar2
        pavtid.ParameterName = "SADJNAMEID"
        pavtid.Direction = ParameterDirection.Input
        pavtid.Value = Trim(sadjnameid)

        Dim pavtType As New OracleParameter
        pavtType.OracleDbType = OracleDbType.Varchar2
        pavtType.ParameterName = "SADJ_NAME"
        pavtType.Direction = ParameterDirection.Input
        pavtType.Value = Trim(sADj_Name)

        Dim pavtCode As New OracleParameter
        pavtCode.OracleDbType = OracleDbType.Varchar2
        pavtCode.ParameterName = "SCOMMENTS"
        pavtCode.Direction = ParameterDirection.Input
        pavtCode.Value = Trim(sComments)

        Dim pavtSecCode As New OracleParameter
        pavtSecCode.OracleDbType = OracleDbType.Varchar2
        pavtSecCode.ParameterName = "SENTERED_BY"
        pavtSecCode.Direction = ParameterDirection.Input
        pavtSecCode.Value = sEntered_BY 'Trim(Me.T_avtcode.Text.ToString)

        Dim pavtDesc As New OracleParameter
        pavtDesc.OracleDbType = OracleDbType.Varchar2
        pavtDesc.ParameterName = "SADJ_STATUS"
        pavtDesc.Direction = ParameterDirection.Input
        pavtDesc.Value = Trim(sADJ_STATUS)

        Dim pAction As New OracleParameter
        pAction.OracleDbType = OracleDbType.Varchar2
        pAction.ParameterName = "SACTION"
        pAction.Direction = ParameterDirection.Input
        pAction.Value = Trim(sACTION)

        cmdOra.Parameters.Add(pavtid)
        cmdOra.Parameters.Add(pavtType)
        cmdOra.Parameters.Add(pavtCode)
        cmdOra.Parameters.Add(pavtSecCode)
        cmdOra.Parameters.Add(pavtDesc)
        cmdOra.Parameters.Add(pAction)

        cmdOra.Connection.Open()
        cmdOra.ExecuteNonQuery()
        cmdOra.Connection.Close()
    Catch ex As Exception
        Session("Error") = ex
        Response.Redirect("ErrorInfo.aspx")
    End Try

End Sub

There is nothing wrong with this code. It works and is easy to understand.

When using clean code principals we can reduce this to something easier to understand. The first thing I noticed when I looked at this function was that there were 6 identical chunks of code that created an oracle parameter. The rule of thumb for clean code is

"If a block of code appears more than once, break it out to a function"

Following this rule I created this function.

Public Function CreateOracleParameter(paramName As String) As OracleParameter
    Dim opParm As New OracleParameter
    opParm.OracleDbType = OracleDbType.NVarchar2
    opParm.ParameterName = Trim(paramName.ToUpper)
    opParm.Direction = ParameterDirection.Input
    opParm.Value = Trim(paramName)
    Return opParm
End Function

Which changed the intial function to;

Protected Sub SaveAdjustment_Names(ByVal sadjnameid As String, ByVal sADj_Name As String, ByVal sComments As String, ByVal sEntered_BY As String, ByVal sADJ_STATUS As String, ByVal sACTION As String)

    Try
        Dim sconstr As New AppFunctions
        Dim oracon As New OracleConnection(sconstr.getConnectionString)

        Dim cmdOra As New OracleCommand
        cmdOra.CommandType = CommandType.StoredProcedure
        cmdOra.CommandText = "WAP.AP_ADJUST_NAME_CHANGE"  '
        cmdOra.Connection = oracon

        cmdOra.Parameters.Add(CreateOracleParameter(sadjnameid))
        cmdOra.Parameters.Add(CreateOracleParameter(sADj_Name))
        cmdOra.Parameters.Add(CreateOracleParameter(sComments))
        cmdOra.Parameters.Add(CreateOracleParameter(sEntered_BY))
        cmdOra.Parameters.Add(CreateOracleParameter(sADJ_STATUS))
        cmdOra.Parameters.Add(CreateOracleParameter(sACTION))

        cmdOra.Connection.Open()
        cmdOra.ExecuteNonQuery()
        cmdOra.Connection.Close()

    Catch ex As Exception
        Session("Error") = ex
        Response.Redirect("ErrorInfo.aspx")
    End Try

End Sub

As you can see much easier to read and thus easier to maintain and trace issues. In this specific case I was able to refactor 168 calls for parameters and reduced the code base by over 20 percent.

Remember there is no wrong way to program, only better ways.

Improve your craft one method at a time.

B

6 Upvotes

8 comments sorted by

3

u/JakDrako Aug 07 '15

Great advice.

Although with 6 parameters, it's not too bad, you could further reduce repetition from:

    cmdOra.Parameters.Add(CreateOracleParameter(sadjnameid))
    cmdOra.Parameters.Add(CreateOracleParameter(sADj_Name))
    cmdOra.Parameters.Add(CreateOracleParameter(sComments))
    cmdOra.Parameters.Add(CreateOracleParameter(sEntered_BY))
    cmdOra.Parameters.Add(CreateOracleParameter(sADJ_STATUS))
    cmdOra.Parameters.Add(CreateOracleParameter(sACTION))

...to:

	For Each param In {sadjnameid, sADj_Name, sComments, sEntered_BY, sADJ_STATUS, sACTION}
		cmdOra.Parameters.Add(CreateOracleParameter(param))	
	Next

1

u/Bonejob VB Guru Aug 07 '15

You are absolutely right. Actually I was wondering about using reflection to find out what parameters are passed into a function...

Parameters and Arrays leads into the next article and how you should never create functions with more than 3 parameters...

Once step at at a time Jak. ;)

1

u/[deleted] Aug 09 '15

How do you recommend dealing with processes that need more than 3 parameters then? Split everything up into smaller functions?

1

u/Bonejob VB Guru Aug 09 '15

Still writing this up. When dealing with more than 3 you use a parameter array.

If all the values are a series you can use a simple array.

Public Function sumNumbers(ByVal numbers() As Integer) As Integer
    dim retVal as integer
    For each num in numbers
        retVal += num
    Next
End Function

use this to call function

Dim addNumbers() As Integer = New Integer() {1,2,3,4,5}
Dim largestNumber As Integer = sumNumbers(testNumbers)

In complex situations you use a ParamArray

Sub studentScores(ByVal name As String, ByVal ParamArray scores() As String)
    Debug.WriteLine("Scores for " & name & ":" & vbCrLf)
    ' Use UBound to determine largest subscript of the array. 
    For i As Integer = 0 To UBound(scores, 1)
        Debug.WriteLine("Score " & i & ": " & scores(i))
    Next i
End Sub

Call studentScores("Anne", "10", "26", "32", "15", "22", "24", "16")
Call studentScores("Mary", "High", "Low", "Average", "High")
Dim JohnScores() As String = {"35", "Absent", "21", "30"}
Call studentScores("John", JohnScores)

I am still working on a param array with custom type so that you can send multiple types into the method. This should give you the base idea.

1

u/[deleted] Aug 09 '15

Thanks for the short writeup! I'm still new to coding but I am working on a simple chart macro in excel where I bring a bunch of parameters into the function to format the chart and I think this will help clean it up a lot.

1

u/[deleted] Aug 17 '15

Is using Trim(sString.toUpper) generally cleaner than using Trim(Ucase(sString))? It looks a bit easier to read to me, don't know if there's any other advantages though (didn't ever think to look into string methods).

1

u/Bonejob VB Guru Aug 17 '15

This is a style thing at this point. Both are easily readable and understandable. I prefer using the string class ToUpper over the Ucase function. I agree with you the the ToUpper is a bit easier to read.

2

u/dan1101 Aug 07 '15

Yep any time you find yourself doing repetitive work on a computer, ask yourself if there is a more concise/automated way to do it.