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?