How to bulletproof the loops

Here is one example about how to bulletproof the loops. This example holds well for legacy code and - of course - for hurry-written-code (that might be the current one, unfortunately).

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

5 Comments

  • Good tips...specially for all the new beginners out there.

  • I understand your issues with ArrayLists, but could you please elaborate what's wrong with IList?
    Afaik, using IList over List basically tells the consumer of the code a thing or two about the intent of the value, doesn't make it any more or less dangerous.

  • IList is just an interface that lists implement. You can use also IList instead of ArrayList in this example.

  • whats wrong with this code?
    Looks pretty similar and works just the same no?

    public void SaveChanges(ArrayList entries)
    {
    if(entries == null)
    continue;

    foreach(MyObject bizObject in entries)
    {
    if(bizObject == null)
    continue;

    if(bizObject.IsDirty)
    bizObject.Save();
    }
    }

  • ArrayList can contain all kinds of objects. If you have objects of class A in ArrayList nothing stops you adding objects of class B there. So, to be safe you should check the object type. Using generic list in this case guarantees that there is no objects of other types.

    If you are using value types then you lose in performance because of unboxing operations.

Comments have been disabled for this content.