Tuesday, April 15, 2008

A Basic Class Design Lesson

Hi Gang,
I'm going through some OLD code today, probably written before classes, but looking at it, I realized it might be a good class design lesson for those not used to writing classes.

The code was in a form, and was actually used multiple times - which by itself says the code should be in a function - code has been changed slightly to obscure the exact nature for my blog, and is in Visual Basic 6.0, but the lesson works for any Object based language


If Left(instanceOfClass.pollclose, 2) > 12 Then
objGrid.Text = (CInt(Left(instanceOfClass.closingTime, 2)) - 12) & ":" & Right(instanceOfClass.closingTime, 2)
Else
objGrid.Text = Left(instanceOfClass.closingTime, 2) & ":" & Right(instanceOfClass.closingTime, 2)
End If


OK (again, VB6 syntax) you could say:

Private Function formatClosingTime(byval theTime as string) as string
If Left(theTime, 2) > 12 Then
formatClosingTime = (CInt(Left(theTime, 2)) - 12) & ":" & Right(theTime, 2)
Else
formatClosingTime = Left(theTime, 2) & ":" & Right(theTime, 2)
End If
end Function


and put that in the form

Which would make the call in the form

objGrid.Text = formatClosingTime(instanceOfClass.closingTime)

- it's ok, and a heck of a LOT better than it was (remember, it's used multiple places - the Don't Repeat Yourself (DRY) concept comes in here)

BUT - that's NOT where the function should really be. What we do is add a Property to the class

Public Function formattedClosingTime() as string
If Left(me.closingTime, 2) > 12 Then
formattedClosingTime = (CInt(Left(me.closingTime, 2)) - 12) & ":" & Right(me.closingTime, 2)
Else
formattedClosingTime = Left(me.closingTime, 2) & ":" & Right(me.closingTime, 2)
End If
End Function


Now, this reduces the code in the form to:

objGrid.Text = instanceOfClass.formattedClosingTime

Isn't that better? The class is taking care of itself. Ahhhh

No comments: