What are the best practices for using Groovy scripts?

You can follow several best practices and recommendations for best performance of your Groovy scripts. Some best practices are covered here based commonly asked questions.

Here are some best practices that you can keep in mind when working with Groovy scripts:
  • Always use a sandbox to test your changes before publishing to mainline.

  • When publishing your sandbox, check for any warnings and don't ignore them. The warnings might cause errors once you publish the sandbox.

  • Whenever you use setAttribute() to set attribute values, add an if statement to check the terminal condition. Otherwise, you might receive a "Post threshold limit reached. Some entities yet to be posted." error.

    For example:

    if(AttributeA != valueA)
     setAttribute('AttributeA', valueA)
  • Use setAttributeValues() to set composite key or related attribute values. For example:

    setAttributeValues(['ReasonWonLostCode','ReasonWonLostCodeSetId'], [xxx,0])  
    setAttributeValues(['DecisionLevelCode','DecisionLevelCodeSetId'], [xxx,0])  
    
  • Create rows using NameValuePairs. For example, to create an Opportunity partner row from the Opportunity object, you can assign an ID as shown below:

    def nvp = new oracle.jbo.NameValuePairs() 
    nvp.setAttribute("OptyId", OpId);
    nvp.setAttribute("PartOrgPartyId", partOrgId);
    nvp.setAttribute("RevnId", primaryRevnId); 
     
    def OptyPartner = getAttribute('RevenuePartnerPrimary')
    def vOP = OptyPartner.createAndInitRow(nvp)
  • Use the ID field instead of the Name field in Groovy logic.

    For example, if SalesStage is the Name field, you should use it for display purpose only. It returns the descriptive name in the user session language. Use SalesStageId, instead.

    Another example is, suppose you're using a dynamic choice list Building_c, use isAttributeChanged('Building_Id_c') instead of its name isAttributeChanged('Building_c').

  • Use Before* triggers instead of After* triggers for better performance, unless you need to overwrite the standard logic.