Last active
July 27, 2016 07:26
-
-
Save jmahmood/730a9718d010fcbe71c9f5b024929c39 to your computer and use it in GitHub Desktop.
Sets vs. Lists in Apex Code in Salesforce.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// original | |
public List<selectOption> getSubCategoryEstimate(){ | |
List<selectOption> options = new List<selectOption>(); | |
if(selectedCategory!=null){ | |
List<Material_Grouping_Estimate__c> listSub = new List<Material_Grouping_Estimate__c>(); | |
listSub = [select Category__c , Sub_Category__c from Material_Grouping_Estimate__c WHERE Category__c like :selectedCategory ORDER BY Sub_Category__c]; | |
if(listSub.get(0).Category__c !=null) { | |
options.add(new SelectOption(listSub.get(0).Sub_Category__c, listSub.get(0).Sub_Category__c)); | |
} | |
for (Integer i = 1; i < listSub.size(); i++) { | |
if(listSub.get(i).Sub_Category__c !=null) | |
if (listSub.get(i).Sub_Category__c != listSub.get(i-1).Sub_Category__c) | |
{ | |
options.add(new SelectOption(listSub.get(i).Sub_Category__c, listSub.get(i).Sub_Category__c)); | |
} | |
} | |
} | |
return options; | |
} | |
// This is wasteful because it is reimplementing items which already exist and are very easy to use. 20 lines. | |
public List<selectOption> getSubCategoryEstimate(String selected_category){ | |
// You should pass a value instead of just depending on state; state can change without you understanding why; passing a value to a function is always easier to debug in SFDC. | |
Set<SelectOption> options = new Set<SelectOption>(); | |
try{ | |
for(Material_Grouping_Estimate__c mge: [select Sub_Category__c from Material_Grouping_Estimate__c WHERE Category__c =: selected_category ORDER BY Sub_Category__c]){ | |
options.add(new SelectOption(mge.Sub_Category__c, mge.Sub_Category__c)); | |
} | |
}catch(System.QueryException e){ | |
// There are no such items. | |
} | |
return new List<SelectOption>(options); | |
} | |
// This is far easier to understand and has the same outcome. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment