Start saving time with snippets
One powerful feature of Eclipse and the Force.com IDE that I’ve recently begun using is snippets. When you find yourself writing the same piece of code repeatedly, create a snippet. I wrote a snippet today to map objects to lists of child objects. This is a task I find myself doing quite often, so it makes sense to have a snippet for it.
To create a snippet in eclipse, highlight the block of code that you want to create your snippet from and right click it. In the context menu select ‘Add to Snippets..’. You will then be prompted to select a category for your snippet or create a new one. After that you are brought into the snippet editor with your chunk of code populated in the ‘Template Pattern’ section. From here you can create variables and put them in your template. After you’ve finished your template click ‘ok’ and your snippet will now be available for resuse.
To use your snippet you need to have the snippet view on your Eclipse layout. To open the snippet view go to Window > show view > snippets. With the snippet view open, double click on the snippet that you want to use, enter in values for the variables you set and hit insert. That’s it.
Here is the snippet I wrote today for mapping objects to lists of child objects:
List<${childObjectType}> ${listName} = new List<${childObjectType}>();
Map<Id,List<${childObjectType}>> ${mapName} =
new Map<Id,List<${childObjectType}>>();
//TODO: populate ${listName}
for(${childObjectType} childObj : ${listName})
{
if(${mapName}.containsKey(childObj.${lookupField}))
{
List<${childObjectType}> childObjs =
${mapName}.get(childObj.${lookupField});
childObjs.add(childObj);
${mapName}.put(childObj.${lookupField}, childObjs);
}
else
${mapName}.put(childObj.${lookupField},
new ${childObjectType}[]{childObj});
}

