Posts Which is easier to read...

Which is easier to read...

... in other words, which is easier to maintain?

chunk = chunk.PadRight(4, " "c).ToLower

                         --  Or  --

chunk = LCase(Left(chunk & Space(4), 4))

I'm converting (or rather resurrecting) some code from VB6 to build a library for some fellow .NET developers and am going through the process of porting various pieces over where it makes sense.  I'm a huge fan of the String class in .NET and prefer it over the some of the built in VB functions.  To me, it just seems easier to read, thus easier to maintain.

On a similar subject, I've been going through converting code that looks like the following:

If variable <> ““ Then


If  Lcase(Mid(variable, 3, 1)) = “d“ Then

The first isn't too bad, however, once I explain why I change the second, the first will probably change as well.  So let's start with the second one.  In order for you to check that some the third character in the variable string is a either an upper or lower cased 'd', this method is creating two new immutable strings in order to check against.  Is there a way to test for this without creating any new strings (that will end up being garbage collected in ring 0)? Yes... here's an example:

If  variable.Chars(2) = “d“c OrElse variable.Chars(2) = “D“c Then

Notice that we are using a value of 2 to check for the 3rd character, since the Chars array is 0 based.  Yes, we have to do the check twice once for upper case and the other for lower case.  But, in this checking, we have not created any new strings (or objects) and purely using numeric type checking.  Now back to the first item.  There is a huge problem with the checking for a string <>.  It's the fact that the string may not be initialized.  So how do we solve this?

If  Not variable Is Nothing AndAlso variable.Length > 0 Then

Just some food for thought... It's Friday and I'm outta here...

Note: Some would refer to these VB functions as being legacy... that is not correct.  Sure, they have a history, but far from being legacy methods.  In some cases, there is functionality within these methods that the String class methods don't handle (or don't handle in the same manner).

This post is licensed under CC BY 4.0 by the author.