vb.net 1.1 -- Better Coding Question

  • Thread starter Thread starter bh
  • Start date Start date
B

bh

If I want to loop through the values in a listbox, and get either all items
in the box, or only selected items, based on a boolean variable passed into
a subroutine, which method would be more efficient?

First Method (test allvalues, first and either loop through all items or
selecteditems, accordingly):

Dim dview As DataRowView
Dim AllValues As Boolean = False
If AllValues = True Then
For Each dview In lstMyListBox.Items
 
BH,

Don't botter to much about loops, probably they take not even 1 promille
from your program.

Cor
 
Hi BH: Nice to see somebody concerned about "better coding" :-)

A couple of points... first you can avoid constructs like "If AllValues =
True" and simply test the value of the variable. Remember it is a boolean
so it's value is basically the result of the test. So code it as "If
AllValues" and you get the same answer.

Now to the point of better coding. It may be more "efficient" in terms of
time to use the SelectedItems property but that isn't the only measure of
better coding. I'd probably opt for traversing the collection and the
reason is (as you've indicated) you can address them all or the selected
subset. Importantly the same loop could address any other property (not
just selected) so if you had to test for any other condition your code would
be very similar. And similarity is good.

From an efficiency standpoint consider using the For Each syntax in your
second example. So basically your routine will visit every item once, test
it for a condition and do something if that condition is met. That's easy
to understand code, that's hard to break code and so that's "better" code.

Tom
 
Thank you! That clears the cobwebs :)

Tom Leylan said:
Hi BH: Nice to see somebody concerned about "better coding" :-)

A couple of points... first you can avoid constructs like "If AllValues =
True" and simply test the value of the variable. Remember it is a boolean
so it's value is basically the result of the test. So code it as "If
AllValues" and you get the same answer.

Now to the point of better coding. It may be more "efficient" in terms of
time to use the SelectedItems property but that isn't the only measure of
better coding. I'd probably opt for traversing the collection and the
reason is (as you've indicated) you can address them all or the selected
subset. Importantly the same loop could address any other property (not
just selected) so if you had to test for any other condition your code
would be very similar. And similarity is good.

From an efficiency standpoint consider using the For Each syntax in your
second example. So basically your routine will visit every item once,
test it for a condition and do something if that condition is met. That's
easy to understand code, that's hard to break code and so that's "better"
code.

Tom
 
Back
Top