You are on page 1of 20
€ FOCUSONFORCE Process Automation and Logic: Basic Apex Given a scenario, use and apply Apex control flow statements De eeu eS eu cn cua (@ roousoyroRcE Table of Contents © = 1000000) { 9 x24; 10 System.debug (‘Value of x: ' + x)5 ly } else { x= 0; System.debug (‘Value of x: ' + x); + (© rocusoworce « Else-If Statement Repeated else if statements can be used, and each condition will be evaluated sequentially ur the expressions evaluates to true, SYNTAX: if (Boolean_Condition 1) ¢ code_btock_1 NBLOCKS else if (BooLean_Condition 2) { Using else if statements allow using as many code blocks are asneeded. Pat code_btock_3 |@ FocusontoRce »| Else-If Statement Example The conditional statement below executes a code block when the value of the num variable satisfies its respective condition, BaF (num 8 x= 35 system.debug (‘Value of x: ) ese irtnum 92 See) { oa =] 1200002) { System.debug (‘Value of x: ' + x)5 } else if(num >= 100000) { xeay System.debug (‘Value of x: ' + x)5 yelse { (@ rocusoyroRce system.debug (‘Value of x: +05 (@ rocusovronce Loops (@ roousovronce ‘A loop is used to repeat a sequence of instructions until a specific condition is met. Loops LOOP TYPES There are five types of procedural loops supported by Apex % Traditional For Loop Listor Set Iteration For Loop © SOQLFor Loop © While Loop © Do-While Loop A traditional for loop executes a block of code repeatedly based on initialization, exit condition, and Traditional Loop increment, = LOOP SYNTAX 2 resltianal foe ln ute the followine eta for (inittalization; condition; increment) ¢ ‘codeblock 2 (@ rocusovronce 2 Traditional Loop ‘The following steps occur when executing this type of for loop: STEP 1 STEP 2 STEP 3 STEP 4 STEPS Theinalzstion | Theloop Thecode The The 8c la statementis continues blockis increment condition is executed first by after checking executed if statementis checked again; the Apex runtime the Boolean the condition executed. the loop engine. Multiple condition. istrue. continues until variables can be the condition is declared and/or false. initialized, (@ roousovrance * Traditional Loop Example The for loop below continuously logs the incrementing value of z as long as the value of fis Werth 10 =a 25+ 26 z+ iy 27 System.debug (‘Value of z: ' + 2)5 28 } eo vexmems Ea List or Set Iteration For Loop The List or Set for loop iterates on each element of a collection of an unknown size. ©) LOOP SYNTAX LIST OR SET VARIABLEDATA —_| VARIABLE TheListor Setiteration | COLLECTION TYPE ‘ASSIGNMENT loopusesthefollowing | Eachelementina The variable datatype | Thevariableis assigned to syntax collection canbe iterated | shouldbectthesame | each element ina list or or Comme vortanees SESE) | by using List or Set datatype contained inthe | setfor which the code 5 ota iteration for loop. listor set collection, blockis executed. (© rocusonronce » List or Set Iteration For Loop Example The following for loop iterates through a collection and prints an Integer during each loop. 1 List numbers = new Integer[]{1,2,3}; 2¥ for(Integer num: numbers) { 3 System.debug (num) ; =a 4 |} (@ rocusovrorce 2s Iterating Collections See considerations below when iterating collections. NOT WRITABLE ERROR THROWN TEMP VARIABLE Itis not possible tomodify a Addition orremovalofelements | Elements can be added toa collection’s elements while while iterating through the temporary list, set, or map, and iterating through it collection that includes them then added or removed to or from causes an error. the original after the loop executionis over, (@ rocusovronce 2 CAA Ene dann —4“— (@ rocusovrorce a UME Fur Luup =a ‘An SOQL for loop processes the results of an SOQL query that is defined in the loop. LOOP SYNTAX, ‘The SOQL for loop uses the following syntax: for (type variable: [S0QL_query]) { code_black ? SOBJECT TYPE Data type ofthe variable should be the same sObject type of the records returned by the SOQL query. SINGLE OR BATCH ‘Query results are processed in batches of 200 records or one record at atime depending on the variable data type used (@ rocusovronce u SOQL For Loop Example The following illustrates how SOQL for loop can process records by batch or one record at a time. operies —unm.pans [omar bens scene [oR ems: —usmcpems [pomucere net 2+ Soc fantace mene] [Str tartan trom contac ONT 31) ¢ SRR or eae _— owning | Sn | Semen Execution Log The following log displays unique record Ids stored in the Set collection variable using the SOQL for loop. Teta | vent (11557024 USER_DEBUG _(5]]BUG)Acout Ds (ul, OL Z0000ExGHAAE 001 2800007BHAA, 0O1Z8000078xGPAA, Oe ere (EithieFrame Elexecuatie [Debug Only Cl Fer Cick Pre tote the fo (© rocusovroRce 2s| While Loop ‘The while loop is used to execute a code block repeatedly as long as a particular condition is true. LOOP SYNTAX The while loop uses the following syntax: ‘while (condition { code, block } LOOP BEHAVIOR The loop evaluates the conditional expression before starting the loop. EVALUATE FIRST So, if the loop condition returns false its code block is not executed. (@ rocusovronce While Loop Example The while loop statement below will keep on printing a string to the debug log as long as the value of jis less than 100. while ( < 100) { system.debug( ‘Value of jz * + J); sees (© rocusoyroRce a| Do-While Loop ‘The do-while loop can be used when the loop needs to be executed at least once. LOOP SYNTAX The do-while loop uses the following syntax: do code,block } while (condition); LOOP BEHAVIOR Similar to the while loop, it executes a code block repeatedly as longasaparticular conditionistruc EVALUATE LATER The do-while loop evaluates the conditional expression after the first loop is executed. (© rocusonrorce a Do-While Loop Example The do-while loop below prints and increments the count variable first before evaluating the conditional expression, Integer count = do { system.debug( ‘Value of count: counts; } while (count < 11); + count); (© rocusoyroRce 29| Break and Continue Statements (@ rocusovtorce Break and Continue Statements All loops in Apex allow for Joop control using break and continue statements. re. Cra. eT tT 7 BREAK STATEMENT. CONTINUE STATEMENT ‘The break statement can be used conditionally within The continue statement can be used conditionally a procedural loop statement to exit the entire loop. within a procedural loop statement to skip the current When encountered, any remaining loop iteration will iteration and jump to the next iteration. When not be executed, encountered ina loop, the current iteration is ion crates and vo teton nh cla will be started, (@ rocusoyroRce The Break Statement The following code snippet shows a while loop that uses a break statement to terminate the loop when a date variable matches the current date. Anteger $= 0; Date mpete = datesnevinetance(2020, 3, 2591 waste) [esen.tosertye mrntey [The break statementisusedhere (Gessij}+——""_ to break the loop and prevent incrementing the count variable, , \ fyotenedebag( "Value of 3 (number of Sterationsyr + 37 ‘The log shows that the loop ran only ‘once. As this code was run on the ‘same date that is stored in the myDate variable, the break statement was tussseae2 —user.penus [[uo|DeBUG wae fran orbs) uuspsnom —useroeus {ruben cot ace 0 immediately executed and the remaining loop iterations terminated, (© rocusonrorce 2 The Continue Statement The following code snippet shows a while loop that uses a continue statement to jump to the next iteration if a date variable matches the current date. tate myoata = dace.nevinstance(2020, 3, 25)¢ wae 3e20004 + Le byotenstoday ps0 mpdaton( ‘As this code was run on the same date that is initially defined in the myDate variable, the Continue statement caused to skip the count incrementation one time, which occured in the first iteration. The succeeding loops do not meet the if statement anymore and, proceed to increment the count variable until the end of the loop. , 6 System debugt valve of S(aunber of Starations)s "+ 3) etscan —vERnemus — [[JOGIGiae al True) sca —venneuc [tmnbemcime metro 9 (@ rocusoyroRce Switch Statements (@ rocusonrorce o Switch Statement A switch statement can be used to determine if an expression matches one of several values and branches SWITCH KEYWORD The keyword switch is used to evaluate an expression. (© rocusonrorce x Switch Statement WHEN KEYWORD The keyword whens used to match values. The when value can bea single value, multiple values, or sObject types. WHEN BLOCK - value matches the switch expression. WHEN ELSE If there is no matching value, the when else code block is ‘executed, which must be the last block in the switch statement. If there isno when else black, no action is taken. (@ rocusovrorce 26| Switch Statement DATA TYPES An expression can be ofthe type Integer, Long, Object, String, or Enum. tis also possible to switch on the result of a method callinstead of a variable expression, NESTED SWITCH Itis possible to nest Apex switch statements to provide multiple execution paths within a when clause. (@ roousovtonce Syntax of a Switch Statement 5] The following shows a sample skeleton switch statement with a when else block to handle a scenario where expression does not match any when value. 1s teh on worsen Hoy shores a] Gesiet Boy , (© rocusovrorce 20 Switch Statement Values Using a switch statement, an expression can be matched against several values represented by when blocks. UNIQUE VALUE Each when value must be unique, and its possible e for avalue to be null MULTIPLE VALUES ‘Awhen block can use multiple, comma-separated literal and enum values, but not both simultaneously. SOBJECT VALUE Only one sObject type can be used per when block. (© rocussntonce » Switch Statement Values A value in a when block can be one of the following: DATA TYPES ‘® Aliteral value of type Integer, Long or 4 String 4 For example,'1’ and customer are literal values. ‘© AnsObject value, For example, ‘Account a! and'Contactc’ are sObject values. % Anenumvalue. For example, SUMMER’ and WINTER’ are values ofan enum defined as Season @ FocusonFoRCe 0 Example of a Switch Statement The switch statement below evaluates the value of a Status custom field on the Account record al updates the Rating field accordingly. (@ rocusovronce =a Execution Log Using the example switch statement, if the Status of the Account record equals to “Sales Deal’, its Rating will be set to “Very Hot’, as shown in the Debug Log below. o7s529m6 USER DEUS (ERG (@ FoousoyroRce A Output ‘The following record detail page highlights the Rating and Status fields that were updated accordingly using the switch statement. D Bage'communietions 4 ton | ervinats pcg Pitney Braso —aonnaan fear Eler-omet aan © operant 5 = xe ey (@ rocusovronce Scenarios and Solutions (@ roousoiroRce Scenarios and Solutions gy RENAN ‘developer is asked to write an application for calculating house rental subsidy for its employees. The conditions are such that if an employee's salary is lesser or equal than a certain minimum amount, the rate of 7.5% is used in calculating the subsidy amount. Ifthe salary is between the minimum and a certain maximum amount, 5% isused. If greater than the maximum amount, the rate is 2.5%, However, ifthe employee has been with the company for more than a certain number of years, 10% is applied regardless ofthe salary amount. ‘earned by the employee. a e Wy — =a Scenarios and Solutions bs raguirecearatortad) { 4 Caatary ce s0809{ Vee BF endary > 900 48 eatery ce 29087¢ pane ; a > ieee ee eee 5] (@ roousovrance Scenarios and Solutions ag) SCENARIO A store sells accessories for parties and special events. It prices its balloons based on their colors as there are colors that are more popular, and others that are harder to find, or more expensive to buy from its stoi deface poled forthe resto the colors How cat thst be trated ingen one ye of conto tow Ao ‘ y (6 rocusoyronce a Scenarios and Solutions ust, “skaver ast, “rainbow, “simnust', ‘chrome! { | esbver slosey', gale ents! ativan mare! ( (© rocussnronce Scenarios and Solutions =a gl SCENARIO ‘Amethod returns a list of sObjects which object types are unknown beforehand as the object type is only determined during run-time, Once the type is determined, afield is updated forall the records. How can an. Apex control flaw be used to handle this requirement? (@ rocusovrorce Scenarios and Solutions EXAMPLE, For (bsuee card: reseed) ten on ecard { en acount ‘ype = "esters » then contact 2 ; : =a tepty() { unate records; ) (@ rocusovrorce gl SCENARIO ‘updating? (@ rocusovrorce Scenarios and Solutions ‘Adeveloper needs to query a large number of records from the database for processing. How can the records be queried from the database that it avoids potential heap size error and DML governor limits when EXAMPLE, Syston aabug(osutte 240035 2 (ering pane ° ren 1) ext ane Loop , > (@ rocusovronce Scenarios and Solutions tor (Ustcoppartunity>eweulte + [SELECT wane, Description ROW Oportunsy]) ¢ tor (portunity 0 + rentee) { onseriotion)) £ Tanta ater fie _g@) SCENARIO Scenarios and Solutions ‘Afeature in an application needs to perform a process that may fail or succeed. fit succeeds, itwill exit the loop and move on. Ifitfail, it will ‘try again. However, it will stop trying after failing a maximum number of times. (@ rocusontorce Scenarios and Solutions fsoolean success = runtyerocess(); fe cauceess) oo DY amiae (ees 55 (@ rocusovrorce Learn More © onsitiona.it-tse) statements o= E @ Ustor set iteration for Loops @ s0aLForLoons @ Lowhile Loos @ ‘erating Collections @ Switchstatements (@ rocusonrorce

You might also like