Article 6DTSJ CodeSOD: Array Length Validation

CodeSOD: Array Length Validation

by
Remy Porter
from The Daily WTF on (#6DTSJ)

Mike sends us some VB.Net code today.

For fileDataCount = 0 To 4 Step 1 Try Dim dataValidate As String = fileData(fileDataCount).ToString Catch ex As Exception error = 1 End TryNext

We enter a loop from 0 to 4, counting by 1. We don't need to specify that, that's the default behavior, but hey, it doesn't hurt to be explicit. Then, in a try/catch, we create a string variable and try and extract an element from the array via the loop counter. If this fails, we set an error flag and keep looping.

The question is: what is this code for? It sets the error flag under two conditions: if an element in the array is null (ToString will fail), or if the array doesn't contain 5 elements.

The validation, in this case, wasn't concerned about nulls: they were just using this block of code to check the array length. Worse, it's technically incorrect, as the array should contain exactly five elements, and this code only checks that it contains at least five elements.

There is, of course, a much simpler way to solve the problem in question: if fileData.Length <> 5, we have an error. And yes, <> is the inequality operator in VB.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments