Click for Part 1, Part 2, Part 3, Part 4 in this series.
Arrays or Lists?
With this post I am, strictly speaking, stepping outside of the pure topic of style. It’s one of those grey areas.
It’s that whole idea of whether to use Array or List data structures in your code. If, like me, you come from a background of programming languages where the first element of an array is element # 1, rather than element # 0, then you may also find List structures a little more intuitive because you usually don’t have to worry about element numbers when you iterate.
From the Apex language viewpoint, arrays and lists are interchangeable; you can declare a list and treat it as an array and vice-versa. Try it yourself if you don’t believe me:
public class BlogStyleGuide5 { // ----------------------------------------------------- // The first method declares and populates an Array, // then iterates through it as a List. // ----------------------------------------------------- void iterateOLI1() { OpportunityLineItem[] arrOLI = [ SELECT Id, Quantity FROM OpportunityLineItem ]; for (OpportunityLineItem iOLI : arrOLI) { Id wrkId = iOLI.Id; Decimal wrkQty = iOLI.Quantity; // Do something } } // ----------------------------------------------------- // The second method declares and populates a List, // then iterates through it as an Array. // ----------------------------------------------------- void iterateOLI2() { List<OpportunityLineItem> lstOLI = [ SELECT Id, Quantity FROM OpportunityLineItem ]; for ( Integer i = 0; i < lstOLI.size(); i++ ) { Id wrkId = lstOLI[i].Id; Decimal wrkQty = lstOLI[i].Quantity; // Do something } } }
If you were to adopt my preference for List structures rather than Arrays, you might end up having to re-code. That’s why I mentioned that this topic steps a little outside the realm of style. Therefore, please use care if you take this route. Ensure you test your changes thoroughly according to standard “good practice”.
Any comments on the above?
January 29, 2013 at 6:45 am
Nice post, Alan!
This is an interesting thing about Apex, for sure. I personally prefer to use lists, but not because of the [0] element issue. Coming from C/C++ a long time ago, I got used to the 1st element being zero.
But when iterating through lists in a for loop, you leave the element counting to the provider as opposed to forcing the reference of the Nth value of a collection, whether it exists or not. Of course, if you start on the wrong element for whatever reason, you’ll either stop one short or go too far, either of which is bad. In general, leaving the decision of what the “next” element in a list should be is, imo, more appropriately handled by the list/iterator provider as opposed to the list consumer.
January 29, 2013 at 8:10 am
Agree 100%, Adam, very well put.
February 18, 2013 at 10:12 pm
Reblogged this on Sutoprise Avenue, A SutoCom Source.