100% found this document useful (1 vote)
299 views59 pages

ADX-231-v.1-Spring 20-Excercise Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
299 views59 pages

ADX-231-v.1-Spring 20-Excercise Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Introduction to OOP Using Apex on the

Lightning Platform
SFADX-231v1-EG
Introduction to Object-Oriented
Programming Using Apex on the
Lightning Platform
Exercise Guide
Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Table of Contents
Exercise 0-1: Preparing Your Training Org 2
Exercise 0-2: Creating a Sandbox Organization 3
Exercise 1-1: Retrieving the Apex Developer Guide 4
Exercise 1-2: Sight-Reading Apex 5
Exercise 2-1: Execute Anonymous in the Developer Console 9
Exercise 3-1: Identifying Constructs 11
Exercise 3-2: Executing Operators in the Developer Console 14
Exercise 3-3: Branching Code with IF Control Statements 16
Exercise 3-4: Iterating Through Code with a FOR Loop 18
Exercise 3-5: Branching code with a Switch Statement instead of an IF ELSE construct 19
Exercise 4-1: Calculating Data with Primitives 20
Exercise 4-2: Iterating Over Lists 22
Exercise 5-1: Creating a Class 24
Exercise 5-2: Using the this Keyword 26
Exercise 6-1: Constructing Objects from Classes 27
Exercise 7-1: Identifying Scope 28
Exercise 9-1: Referencing sObjects in Apex 32
Exercise 9-2: Saving sObjects in Apex 33
Exercise 10-1: Creating SOQL to Return Data to Apex 34
Exercise 11-1: Coding a Trigger Part I 36
Exercise 11-2: Coding a Trigger Part II 38
Exercise 11-3: Refactoring a Trigger Using a Class 40
Exercise 12-1: Debugging Problematic Code 42
Exercise 12-2: Handling Exceptions 45
Exercise 13-1: Programming a Unit Test 47
Exercise 14-1: Deploying to Production 48
Exercise 16-1: Sight-Reading Apex 50
Exercise 16-2: Coding the Final Project 54

©Copyright 2020 salesforce.com, inc. All rights reserved. 1


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 0-1: Preparing Your Training Org

Goal:
Prepare your org for classroom activities and access after class.
Scenario:
Universal Containers wants you to do development tasks for them. You have been given a
Salesforce organization that you need to set up to begin your work. You want to make sure that
all system messages from the org come to you.
Tasks:
1. Update the email address on your user record.
2. Optional: Install the Salesforce mobile application.
3. Download and extract the lab files.
Time:
10 minutes

Instructions:
1. Update the email address on your user record.
A. In a browser, go to http://login.salesforce.com.
B. Enter the login credentials provided by your instructor.
C. Click Admin Avatar | Settings | Personal Information.
i. Email: Enter an email you can access from the classroom
ii. First Name: Enter your first name
iii. Last Name: Enter your last name
D. Click Save.
Optional: Install the Salesforce mobile application.
E. Navigate to the app store on your supported device.
F. Search for Salesforce.
G. Install the app on your device.

2. Download your lab files from the File tab.


A. From the App Launcher, find and open Files.
B. Download ADX231_IntroToOOPUsingApexLabFiles.zip file to your desktop.
C. Extract the files:
i. Windows – Right-click the zip folder, click Extract All, and click Extract.
ii. Mac – Double-click the zip folder to extract its files to an unzipped folder in the
same directory.

©Copyright 2020 salesforce.com, inc. All rights reserved. 2


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 0-2: Creating a Sandbox Organization

1. Customize the admin user to use your email.


A. Log in to your Universal Containers production organization at
http://login.salesforce.com.
B. Navigate to Admin Avatar | Settings | Personal Information.
C. Modify the Email field to be an email you can access during class.
D. Click Save.

2. Create the sandbox (full) organization.


A. Navigate to Setup | Sandboxes.
B. Click New Sandbox.
C. On this screen, where you add Sandbox Information and choose the Sandbox
License:
i. Name: Dev
ii. Description: This is a development environment.
iii. Under the Full column, click Next.
D. On this screen, choose your Sandbox Options:
i. Object data included: All
ii. Include Chatter Data: Select
iii. Click Create.

Note: The time it takes to complete the full copy will depend on the length of the queue at
the time requested. You will receive an email (sent to the email address specified in your
user profile) letting you know when it has been completed.

Review

1. Why are you creating a sandbox?

©Copyright 2020 salesforce.com, inc. All rights reserved. 3


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 1-1: Retrieving the Apex Developer Guide

1. Review the Apex Code Developer’s Guide.


A. Open a browser window and navigate to the Salesforce Developers website:
http://developer.salesforce.com
B. From the site menu, navigate to Resources | Documentation.
C. Scroll down to locate the Apex Developer Guide. Click on it to view the HTML
version of the guide.
D. Right-click the PDF Download link. Save the PDF to your desktop by choosing Save
Link As.

2. Review the Apex Code Cheat Sheet. (Optional)


A. In a web browser, navigate to:
https://developer.salesforce.com/page/Cheat_Sheets
B. Locate, download, and review the App Logic: Apex Code Cheat Sheet. The Cheat
Sheet is a handy guide to Apex syntax.

Review

1. What type of information can you find in the Reference section of the Developer’s
Guide?

2. Does the Developer’s Guide contain the full specifications for SOQL syntax?

©Copyright 2020 salesforce.com, inc. All rights reserved. 4


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 1-2: Sight-Reading Apex

1. Read the code block on the following page. Fill out the worksheet with your guess as to
what you believe is happening on each corresponding line of code. Note: The code line
numbers correspond with the worksheet line numbers.

Review

1. How is the code in lines 1–14 fundamentally different from lines 15–33?

2. What is this code doing?

©Copyright 2020 salesforce.com, inc. All rights reserved. 5


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Code

01 public class Updater{


02 public void updateFirstContact(List<Contact> listOfContacts){
03 if(listOfContacts!= null && (!listOfContacts.isEmpty())){
04 Contact firstContact = listOfContacts.get(0);
05 if(firstContact.id != null){
06 firstContact.firstName += '-updated';
07 firstContact.lastName = firstContact.lastName + '-updated';
08 update firstContact;
09 }
10 } else {
11 System.debug('There are no contacts in the list');
12 }
13 }
14 }

15 Account theAccount = new Account(name = 'My First Account');


16 Database.insert(theAccount);
17 System.debug('The new Account Id is ' + theAccount.id);
18 List<Contact> contactList = new List<Contact>();
19 for(Integer iCounter = 0; iCounter <= 5; iCounter++){
20 Contact oneContact = new Contact();
21 oneContact.accountId = theAccount.id;
22 oneContact.firstName = 'testFirst' + iCounter;
23 oneContact.lastName = 'testLast' + iCounter;
24 contactList.add(oneContact);
25 System.debug('Added to list contact #' + iCounter);
26 }
27 List<Database.SaveResult> saveResults =
Database.insert(contactList);

28 Integer howManyContacts = [ SELECT count() FROM Contact


WHERE accountId=:theAccount.id ];
29 System.debug('The account has ' + howManyContacts + ' contacts.');
30 System.debug(contactList.get(0));
31 Updater myUpdater = new Updater();
32 myUpdater.updateFirstContact(contactList);
33 System.debug(contactList.get(0));

©Copyright 2020 salesforce.com, inc. All rights reserved. 6


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Worksheet

01 __________________________________________________________________

02 __________________________________________________________________

03 __________________________________________________________________

04 __________________________________________________________________

05 __________________________________________________________________

06 __________________________________________________________________

07 __________________________________________________________________

08 __________________________________________________________________

09 __________________________________________________________________

10 __________________________________________________________________

11 __________________________________________________________________

12 __________________________________________________________________

13 __________________________________________________________________

14 __________________________________________________________________

15 __________________________________________________________________

16 __________________________________________________________________

17 __________________________________________________________________

18 __________________________________________________________________

19 __________________________________________________________________

20 __________________________________________________________________

21 __________________________________________________________________

22 __________________________________________________________________

23 __________________________________________________________________

24 __________________________________________________________________

25 __________________________________________________________________

©Copyright 2020 salesforce.com, inc. All rights reserved. 7


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

26 __________________________________________________________________

27 __________________________________________________________________

28 __________________________________________________________________

29 __________________________________________________________________

30 __________________________________________________________________

31 __________________________________________________________________

32 __________________________________________________________________

33 __________________________________________________________________

©Copyright 2020 salesforce.com, inc. All rights reserved. 8


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 2-1: Execute Anonymous in the Developer Console

1. Execute code in the Execute Anonymous Window.


A. Ensure that you are logged in to your Sandbox organization. (Use your Production
Org if your Sandbox Org is not available yet.)
B. Click the Developer Console from the Gear icon.
C. Type CTRL+E to open the Execute Anonymous Window.
D. Click the small arrow button in the upper right-hand corner of the Execute
Anonymous Window to pop the window out.
E. Copy and paste the contents of the 2-1.ExecuteAnonymous.txt from the Exercises
folder into the Execute Anonymous Window.
F. Select the Open Log checkbox.
G. Click Execute to run the code in Execute Anonymous Window.
H. Type CTRL+W to close the Execute Anonymous Window.
I. You will see the Debug view. Navigate to Debug | Switch Perspective | Log Only
(Predefined) to see just the logs. If you prefer, select the Debug Only checkbox to
filter your results and only show the output of the System.debug statements.
J. To close all open windows, type CTRL+ALT+/.
K. Close the Developer Console and return to your Sandbox org.

2. Verify the results of running the code.


A. From the App Launcher , find and select the Account item.

B. Change the List View dropdown to All Accounts.


C. Drill into the account named My First Account, and verify there are 6 contacts
associated to the account.

©Copyright 2020 salesforce.com, inc. All rights reserved. 9


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

3. Try out your own code.

A. Click the Developer Console from the Gear icon.


B. Type CTRL+E to open the Execute Anonymous Window.
C. Delete the code you had previously pasted into the Execute Anonymous window.
D. Type the following code into the Execute Anonymous Window.
System.debug('Hello World!');
System.debug('My name is enter_your_name_here');
E. Select the Open Log checkbox.
F. Click Execute to run the code.
G. If you see the Debug view, navigate to Debug | Switch Perspective | Log Only
(Predefined) to see just the logs.
F. Verify that the log shows the debug information you requested in your code.
G. To close all open windows, type CTRL+ALT+/.
H. Close the Developer Console and return to your Sandbox org.

Review

1. What are the advantages and disadvantages of using Execute Anonymous?

2. Do anonymous blocks execute under the privileges of the System or the current user?

©Copyright 2020 salesforce.com, inc. All rights reserved. 10


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 3-1: Identifying Constructs

Part A – Match the code snippet with its construct name (Note: There are 3 of each
construct):

Programming Construct Names


(There are 3 of each in the table below)

a. class

b. method

c. attribute

d. comment

e. constant

f. keyword

# Snippet Which Construct is This?

1 contactDedupe()

2 ContactDedupe{}

3 CONTACT_DEDUPE

4 Protected

5 contactDedupe

6 // contactDedupe

7 Public

8 ADD_PRODUCT

9 AddProduct{}

©Copyright 2020 salesforce.com, inc. All rights reserved. 11


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

10 addProduct()

11 /* addProduct */

12 addProduct

13 // commissionCalc

14 commissionCalc

15 Private

16 COMMISSION_CALC

17 CommissionCalc{}

18 commissionCalc()

©Copyright 2020 salesforce.com, inc. All rights reserved. 12


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Part B – Draw in curly braces around code blocks where needed (or use the file in the
Exercises folder).
01 List<Contact> contactList = new List<Contact>();
02 for(Integer iCounter=0; iCounter <= 5; iCounter++)
03 for(Integer jCounter=0; jCounter <= 10; jCounter++)
04 if(iCounter < jCounter)
05 System.debug('iCounter is less than jCounter');
06 Integer k=iCounter;
07 while(k < jCounter)
08 System.debug('k < jCounter');
09 k++;
10
11
12 else
13 System.debug('iCounter is not less than jCounter');
14
15
16
17 public class ContactCounter
18 public void countSmithContacts(List<Contact> listOfContacts)
19 // the code of the method goes here…
20 Integer smithCounter = 0;
21 for(Contact c : listOfContacts)
22 if(c.lastname=='Smith')
23 smithCounter++;
24 System.debug('Smith #' + smithCounter);
25
26
27
28

Review

1. What are the two ways to write comments into your code? What is the difference
between the two different methods of writing comments?

2. Are the naming conventions used in Part A requirements or are they best practices?

©Copyright 2020 salesforce.com, inc. All rights reserved. 13


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 3-2: Executing Operators in the Developer Console

1. Execute System.debug statements to test operator usage and syntax.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Before entering the following in the Execute Anonymous Window, try to guess what
the outcome of the following statement will be. Once you’ve entered the code,
select the Open Log checkbox, if it’s not already selected. Click Execute to execute
the code.

System.debug(true && true);

D. If you see the Debug view, navigate to Debug | Switch Perspective | Log Only
(Predefined) to see just the logs.
E. Note the result in the log. If you prefer, select the Debug Only checkbox to filter your
results and only show the output of the System.debug statements. How did it
compare to your guess?
F. Before entering the following in the Execute Anonymous Window, try to guess what
the outcome of the following statements will be. Then click Execute to execute the
code when ready:

Guessed Actual
# Snippet
Outcome? Outcome

1 System.debug(true && false);

2 System.debug(true || false);

3 System.debug(-2 + 2);

4 System.debug('truthi' + 'ness');

5 System.debug('a' == 'a');

6 System.debug('a' != 'aa');

7 System.debug(('a' != 'aa') && (3>=4));

8 System.debug((3*5)>=(30/2));

©Copyright 2020 salesforce.com, inc. All rights reserved. 14


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

9 System.debug(!(5*5 == 25));

10 System.debug((5*5 != 25)||(true));

11 System.debug('test' != 'test');

12 System.debug((false && true)||(true && true));

G. To close all open windows, type CTRL+ALT+/.


H. Close the Developer Console and return to your Salesforce org.

Review

1. What is the difference between the = operator and the == operator?

2. What does the ! operator do?

©Copyright 2020 salesforce.com, inc. All rights reserved. 15


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 3-3: Branching Code with IF Control Statements

1. Create and execute an anonymous block using the sample code.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Click the arrow in the top right-hand corner of the Execute Anonymous Window to
pop the window out.
D. Type the following code into the Execute Anonymous Window:

String stateAbbreviation = 'IL';


String stateName;
if (stateAbbreviation == 'IL') {
stateName = 'Illinois';
}
System.debug('State = ' + stateName);

E. What will be output to the log if you execute the code? ______________
F. Click Execute to execute your code, and then close the Execute Anonymous
Window to check the run log.

2. Modify/extend the given code to check for additional states.


A. Type CTRL+E to open the Execute Anonymous window.
B. Copy the code from the 3-3.BranchingCodeWithIFStatements.txt file in the
Exercises folder and paste it into the Execute Anonymous Window (replacing any
default text).
C. Complete the TODO: sections as required.

3. Test your code.


A. Change the value of the stateAbbreviation variable.
B. If the Open Log checkbox is not selected, select it.
C. Click Execute to execute the code.
D. Type CTRL+W to close the Execute Anonymous Window.
E. If you see the Debug view, navigate to Debug | Switch Perspective | Log Only
(Predefined) to see just the logs. View the results of running your code.
F. To close all open windows, type CTRL+ALT+/.
G. Close the Developer Console and return to your org.

Review

©Copyright 2020 salesforce.com, inc. All rights reserved. 16


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

1. How do we structure our IF control blocks to execute a default block of code when the
IF logic tests all evaluate to false?

2. If, like the exercise, we want to check for all 50 states, do we have to use repetitive IF-
ELSE blocks or can we use a switch/case structure?

©Copyright 2020 salesforce.com, inc. All rights reserved. 17


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 3-4: Iterating Through Code with a FOR Loop

1. Create an anonymous block that contains a FOR loop that iterates over an integer from
0 to 6 (i.e., 7 total passes through the loop), and outputs the corresponding day of the
week.
A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Copy the code from the 3-5.IteratingWithFORLoops.txt file in the Exercises folder
and paste it into the Execute Anonymous Window (replacing any default text).
D. Complete the TODO: sections as required.
E. Click Execute to execute the code, and then close the Execute Anonymous Window
to view the logs. Do you see all the days of the week in the execution log?
F. To close all open windows, type CTRL+ALT+/.
G. Close the Developer Console and return to your org.

2. Extra Credit: Create an anonymous block of code that uses a loop to calculate and
output the unique Fibonacci numbers less than 100. Fibonacci numbers are: 0, 1, 1, 2,
3, 5, 8, 13, 21, 34, 55, etc.
A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Write code to calculate and output the Fibonacci numbers under 100.
D. Click Execute to execute the code, and then close the Execute Anonymous Window
to view the logs.
E. To close all open windows, type CTRL+ALT+/.
F. Close the Developer Console and return to your org.

Review

1. How would we perform the same loop, but count down from 7 to 1 instead?

2. What is the difference between a while loop and do-while loop?

©Copyright 2020 salesforce.com, inc. All rights reserved. 18


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 3-5: Branching code with a Switch Statement instead of an IF ELSE construct

1. Modify/extend the given code to output the day of the week.


A. Type CTRL+E to open the Execute Anonymous window.
B. Copy the code from the 3-5.BranchingCodeWithSwitchStatement.txt file in the
Exercises folder and paste it into the Execute Anonymous Window (replacing any
default text).
C. Complete the TODO sections as required.

©Copyright 2020 salesforce.com, inc. All rights reserved. 19


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 4-1: Calculating Data with Primitives

1. Open the Developer Console’s execute anonymous window.


A. Click the Developer Console from the Gear menu.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Before entering the following in the Execute Anonymous Window, try to guess what
the outcome of the following debug statement will be. Then click Execute to
execute the code when ready:

Boolean b;
Boolean bIsNull;
if(b == null){
bIsNull = true;
} else {
bIsNull = false;
}
System.debug(bIsNull);

D. Close the Execute Anonymous Window and note the result. How did it compare to
your guess? Now repeat step C, completing the TODOs, for each of the following
code snippets:
i.
/* TODO: Declare a string = 'he' */
/* TODO: Declare a string = 'llo' */
/* TODO: Add the two strings you declared above together into a
variable named s */
Boolean b;
if(s=='hello'){
b = true;
} else {
b = false;
}
System.debug(b);

ii.
Integer i = 1;
Integer j = 2;
while(i < 3){
/* TODO: Set j equal to i multiplied by j */
/* TODO: Increment the i variable by 1 */
}
System.debug('The integer j = ' + j);

©Copyright 2020 salesforce.com, inc. All rights reserved. 20


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

E. To close all open windows, type CTRL+ALT+/.


F. Close the Developer Console and return to your Salesforce org.

Review

1. Are all variables null until they are initialized?

2. Is an empty string (for example, String s = '';) the same as null?

©Copyright 2020 salesforce.com, inc. All rights reserved. 21


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 4-2: Iterating Over Lists

1. Open the Developer Console’s Execute Anonymous Window.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Before entering the following in the Execute Anonymous Window, try to guess what
the outcome of the following debug statement will be. Then click Execute to
execute the code when ready:

String myFirstString = 'Hello';


String mySecondString = 'World!';
List<String> myStringList = new List<String>();
myStringList.add(myFirstString);
myStringList.add(mySecondString);
System.debug(myStringList);

D. Close the Execute Anonymous Window and note the result. How did it compare to
your guess? Now repeat step C, completing the TODOs, for each of the following
code snippets:
i.
String myFirstString = 'Hello';
String mySecondString = 'World!';
List<String> myStringList = new List<String>();
myStringList.add(myFirstString);
myStringList.add(mySecondString);
String allTogether = '';
/* TODO: Loop through myStringList by incrementing an
integer variable until it reaches the size of
myStringList */
/* TODO: Inside the loop, retrieve the element from the list
corresponding to the integer variable and add it to the
allTogether variable */
System.debug(allTogether);

©Copyright 2020 salesforce.com, inc. All rights reserved. 22


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

ii.
String myFirstString = 'Hello';
String mySecondString = 'World!';
List<String> myStringList = new List<String>();
myStringList.add(myFirstString);
myStringList.add(mySecondString);
String allTogether = '';
/* TODO: Loop through myStringList without using an integer
variable, but instead using a String variable */
/* TODO: Inside the loop, take the current element of the list
and add it to the allTogether variable */
System.debug(allTogether);

E. To close all open windows, type CTRL+ALT+/.


F. Close the Developer Console to return to your Salesforce org.

Review

1. When we use the add() method to add elements to a List, in what order does the new
element get added?

2. In example 1-d-i, why do we use i<myStringList.size() instead of


i<=myStringList.size()?

©Copyright 2020 salesforce.com, inc. All rights reserved. 23


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 5-1: Creating a Class

1. Create the Dog class.


A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Class.
C. Enter the name Dog and click OK .
D. Copy the code from the 5-1.DogClass.txt file in the Exercises folder and paste it into
the Developer Console (replacing any default text).
E. Complete the TODOs as required.
F. Save the class by typing CTRL+S. Check the Problems tab at the bottom of the
Developer Console to see if you have any errors in your class that prevented the
class from saving to the server.

2. Test the class.


A. Type CTRL+E to open the Execute Anonymous Window.
B. Enter the following code in the Execute Anonymous Window, replacing any text in
the window. Try to guess what the result will be, and then click Execute to execute:

Dog myDogFido = new Dog();


myDogFido.play();
String myDogFidoStatus = myDogFido.getStatus();
System.debug('Fido is currently ' + myDogFidoStatus);

C. Close the Execute Anonymous Window and note the result. How did it compare to
your guess?
D. Try to make Fido sit and wag his tail, as well.
E. To close all open windows, type CTRL+ALT+/.
F. Close the Developer Console and return to your Salesforce org.

3. Extra Credit: Assign the dog a gender and adjust the wagTail() method to say
'wagging his tail' or 'wagging her tail'. For further extra credit, make
gender an Enum instead of a String.

©Copyright 2020 salesforce.com, inc. All rights reserved. 24


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Review

1. What happens if we change the first line of our anonymous block (step 2-a) to read Dog
myDogFido;?

2. Why does the getStatus() method in the Dog class return a String instead of void?

©Copyright 2020 salesforce.com, inc. All rights reserved. 25


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 5-2: Using the this Keyword

1. Modify the class named Dog, giving it name and playmate attributes. Update the
play()method to receive a Dog as a parameter and set the playmate attribute equal to
the Dog passed in.
A. Click the Developer Console from the Gear icon.
B. Type CTRL+SHIFT+O to bring up the Open Resource dialog.
C. Type Dog to filter the list, then select the Dog.apxc Apex class and click Open.
D. Copy the code from the 5-2.PassingMethodParameters.txt file in the Exercises folder
and paste it into the Developer Console (replacing any default text).
E. Complete the TODO sections as required.
F. Save the class by typing CTRL+S. Check the Problems tab at the bottom of the
Developer Console to see if you have any errors in your class that prevented the
class from saving to the server.

2. Test the class using the anonymous code provided.


A. Type CTRL+E to open the Execute Anonymous Window.
B. Copy the code from the 5-2.PassingMethodParameters_ExecuteAnonymous.txt file
in the Exercises folder. Paste it into the Execute Anonymous Window. Try to guess
what the outcome of the code snippet will be, and then click Execute to execute the
code when ready.
C. Close the Execute Anonymous Window and note the result. How did it compare to
your guess?
D. To close all open windows, type CTRL+ALT+/.
E. Close the Developer console and return to your org.

3. Extra credit: Use the play() method on the dog’s playmate to get the dogs to
play together. Use the 05-2.Extra.PassingMethodParameters.txt and 05-
2.Extra.PassingMethodParameters_ExecuteAnonymous.txt files. Be careful
of infinite loops.

Review

1. What does the this keyword represent when used in the play method?

©Copyright 2020 salesforce.com, inc. All rights reserved. 26


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 6-1: Constructing Objects from Classes

1. Modify the class named Dog, giving it two different constructors.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+SHIFT+O to bring up the Open Resource dialog.
C. Type Dog to filter the list, then select Dog.apxc and click Open.
D. Copy the code from the 6-1.ConstructingObjectsFromClasses.txt file in the Exercises
folder, and paste it into the Developer Console (replacing any default text).
E. Complete the TODO sections as required.
F. Save the class by typing CTRL+S. Check the Problems tab at the bottom of the
Developer Console to see if you have any errors in your class that prevented the
class from saving to the server.

2. Test the class using the provided execute anonymous code.


A. Type CTRL+E to open the Execute Anonymous Window.
B. Copy the code from the 6-1.ConstructingObjectsFromClasses_
ExecuteAnonymous.txt file in the Exercises folder. Paste it into the Execute
Anonymous Window. Try to guess what the outcome of the code snippet will be and
then click Execute to execute the code when ready.
C. Close the Execute Anonymous Window and note the result. How did it compare to
your guess?
D. To close all open windows, type CTRL+ALT+/.
E. Close the Developer Console and return to your org.

Review

1. In the one-parameter constructor, is it necessary to use the this keyword to set the
name attribute?

2. What term do we use to describe two or more methods with the same name in a class?

©Copyright 2020 salesforce.com, inc. All rights reserved. 27


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 7-1: Identifying Scope

1. Review the sample code below and answer all the review questions.

Code

01 global class Dog {


02
03 /*** Attributes ***/
04 public String name;
05 private String status;
06 private Dog playmate;
07 private String color;
08
09 /*** Accessor Methods ***/
10 public String getStatus(){
11 return status;
12 }
13
14 public String getPlaymateName(){
15 if(status=='Playing'){
16 return playmate.name;
17 } else {
18 return null;
19 }
20 }
21
22 public String getColor(){
23 if(color==null) setColor('Black');
24 return color;
25 }
26
27 public void setColor(String newColor){
28 color = newColor;
29 }
30
31 /*** Constructors ***/
32 global Dog(){
33 this('MysteryDog');
34 }
35
36 global Dog(String nameOfDog){
37 this.name = nameOfDog;
38 }
39
40 /*** Action Methods ***/
41 public void sit(){

©Copyright 2020 salesforce.com, inc. All rights reserved. 28


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

42 status = 'Sitting';
43 }
44
45 public void play(Dog newPlaymate){
46 status = 'Playing';
47 // need the IF condition to avoid an infinite loop
48 if(playmate != newPlaymate) {
49 playmate = newPlaymate;
50 newPlaymate.play(this);
51 }
52 }
53
54 public void wagTail(){
55 status = 'Wagging Tail';
56 }
57 }

Review

1. Is the name attribute accessible outside the Dog class? Why?

2. Is the color attribute accessible outside the Dog class? Why?

3. Is the name attribute accessible from outside the org of the Dog class? Why?

4. Can an instance of the Dog class be declared outside the application that the Dog class
is a part of if the Dog class’ application is installed in the Salesforce org? Why?

©Copyright 2020 salesforce.com, inc. All rights reserved. 29


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

5. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog('Fido');
Dog toby = new Dog('Toby');
fido.playmate = Toby;

6. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog('Fido');
Dog toby = new Dog('Toby');
fido.play(toby);
System.debug(fido.playmate.name);

7. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog('Fido');
Dog toby = new Dog('Toby');
fido.play(toby);
System.debug(fido.getPlaymateName());

8. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog('Fido');
fido.sit();
fido.setColor('Red');
System.debug(fido.status);
System.debug(fido.getColor());

©Copyright 2020 salesforce.com, inc. All rights reserved. 30


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

9. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog('Fido');
fido.setColor('Red');
System.debug(fido.getColor());

10. What is the outcome of the following code (assume it is run in the Execute Anonymous
window)?
Dog fido = new Dog();
Dog toby = new Dog('Toby');
fido.play(toby);
String s = toby.getPlaymateName();
System.debug(s);

©Copyright 2020 salesforce.com, inc. All rights reserved. 31


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 9-1: Referencing sObjects in Apex

1. Create the OfferGenerator class.


A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Class.
C. Enter the Name OfferGenerator and click OK .
D. Copy the code from the 9-1.OfferGeneratorClass.txt file in the Exercises folder and
paste it into the OfferGenerator Developer Console window (replacing any default
text).
E. Complete the TODO sections as required.
F. Save the class by typing CTRL+S.

2. Execute the class via an anonymous block.


A. Type CTRL+E to open the Execute Anonymous Window.
B. Copy the code from the 9-1.ExecuteAnonymous.txt file in the Exercises folder and
paste it into the Execute Anonymous Window.
C. Click Execute to execute the code.
D. Close the Execute Anonymous Window.
E. To close all open windows, type CTRL+ALT+/.
F. Close the Developer Console and verify that a new record was created in your org.

3. Extra credit: Modify the class and anonymous block to return the Id of the newly
created record:

Review

1. In an sObject, what is accessed on the right side of the dot in dot notation?

2. What type of relationship, parent-to-child or child-to-parent, is Job_Application__c


on Offer__c? What is the name of the relationship?

©Copyright 2020 salesforce.com, inc. All rights reserved. 32


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 9-2: Saving sObjects in Apex

1. Modify the OfferGenerator class.


A. Open the Developer Console from the Gear icon.
B. Type CTRL+SHIFT+O to access the Open Resource window. From there, open the
OfferGenerator class.
C. Copy the code from the 9-2.OfferGeneratorClass.txt file in the Exercises folder and
paste it into the OfferGenerator editor window (replacing any default text).
D. Complete the TODO sections as required.
E. Save the class.

2. Execute the class using an anonymous block.


A. Copy the code from the 9-2.ExecuteAnonymous.txt file in the Exercises folder and
paste it into the Execute Anonymous window.
B. Complete the TODO sections as required.
C. Click Execute to execute the code, and then close the Execute Anonymous window.
In step F, you will verify if the code executed properly.
D. To close all open windows, type CTRL+ALT+/.
E. Close the Developer Console.
F. Verify that a new candidate, job application, and offer record has been created.

Review

1. What method on the Database.SaveResult object is used to verify success of a DML


operation? Where could we add this check in the three methods in the OfferGenerator
class?

2. Consider the code below. How many Database.SaveResult objects are returned?
List<Account> newAccounts = new List<Account>();
Account newAccountOne = new Account(Name='Acme');
newAccounts.add(newAccountOne);
Account newAccountTwo = new Account(Name='XYX Inc.');
newAccounts.add(newAccountTwo);
Database.SaveResult[] results = Database.insert(newAccounts);
System.debug(results.size());

©Copyright 2020 salesforce.com, inc. All rights reserved. 33


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 10-1: Creating SOQL to Return Data to Apex

1. Create a query using the Developer Console.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+SHIFT+O to bring up the Open Resource dialog.
C. Type Candidate to filter the list, then select Candidate__c.obj and click Open.
D. Hold down the CTRL key on your keyboard and click to select the following fields
from Candidate__c:
i. Id
ii. Name
iii. First_Name__c
iv. Last_Name__c
v. Email__c
vi. Years_of_Experience__c
E. Create a query that queries these fields by clicking Query.
F. Click inside the generated query. Add the following WHERE clause to the end of the
query: WHERE Years_of_Experience__c >= 5
G. Click Execute. You should see the screen refresh with the results of the query. Does
every candidate listed have at least 5 years of experience?

2. Add the query to a class.


A. Navigate to File | New | Apex Class.
B. Enter the name CandidateExperience and click OK .
C. Copy the code from the 10-1.CandidateExperienceClass.txt file in the Exercises
folder and paste it into the CandidateExperience editor window (replacing any
default text).
D. Complete the TODO sections as required.
E. Type CTRL+S to save the class.

3. Execute the class using an anonymous block.


A. In the Execute Anonymous window, create an instance of the CandidateExperience
class.
B. Call the getCandidatesWithExperience method, passing 5 as the parameter.
C. Verify that a list with eight records was returned.
D. To close all open windows, type CTRL+ALT+/.
E. Close the Developer Console and return to your org.

4. Extra credit: Output the list of candidates, including the Id, First Name, and Last Name.

©Copyright 2020 salesforce.com, inc. All rights reserved. 34


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Review

1. If the fields in the SELECT list were replaced with a count() what would be returned?

2. What had to be modified with the query in order for it to work in the class?

©Copyright 2020 salesforce.com, inc. All rights reserved. 35


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 11-1: Coding a Trigger Part I

1. Create a new trigger.


A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Trigger.
C. Enter the following information:
i. Name: JobAppForCandidate
ii. sObject: Candidate__c
D. Click Submit.
E. Copy the code from the 11-1.JobAppForCandidate.txt file in the Exercises folder and
paste it into the JobAppForCandidate editor window (replacing any default text).
F. Complete the TODO sections as required.
G. Type CTRL+S to save the trigger.
H. To close all open windows, type CTRL+ALT+/.
I. Close the Developer Console and return to your Salesforce org.

2. Create a new candidate to test the trigger.


A. In Salesforce, click the Candidates tab.
B. Click New.
C. Fill out the following fields:
i. First Name: John
ii. Last Name: Smith
iii. Gender: Male
iv. Street Address 1: 1234 F St
v. City: Washington
vi. State: DC
vii. Zip: 20008
viii. Country: USA
D. Click Save.
E. View the Job Applications section on the Related tab. Verify that a new job
application is listed.
F. Click the down arrow and Edit in the job application record row.
G. Click the Position Lookup icon.
H. Select Black Box Tester . You may need to search for it if does not automatically
appear.
I. Click Save.

©Copyright 2020 salesforce.com, inc. All rights reserved. 36


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Review

1. How many records are operated on when Trigger.new[0] is accessed?

2. JobAppForCandidate trigger operates after insert. In terms of order of execution,


what occurs right before this trigger executes?

©Copyright 2020 salesforce.com, inc. All rights reserved. 37


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 11-2: Coding a Trigger Part II

1. Update your JobAppForCandidate trigger to handle bulk data.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+SHIFT+O to bring up the Open Resource dialog.
C. Type JobApp to filter the list, then select JobAppForCandidate.apxt and click Open.
D. In the JobAppForCandidate trigger, copy the code from the 11-
2.JobAppForCandidateTrigger.txt file in the Exercises folder and paste it into the
JobAppForCandidate editor window (replacing any default text).
E. Complete the TODO sections as required to update the trigger to handle bulk data.
Note: If you had code working before, you may copy and paste the working code
into the appropriate place in the trigger.
F. Type CTRL+S to save the trigger.
G. To close all open windows, type CTRL+ALT+/.
H. Close the Developer Console and return to your org.

2. Create a new candidate to test the trigger.


A. In Salesforce, click the Candidates tab.
B. Click New.
C. Fill out the following fields:
i. First Name: Sam
ii. Last Name: Smith
iii. Gender: Male
iv. Street Address 1: 1234 F St
v. City: Washington
vi. State: DC
vii. Zip: 20008
viii. Country: USA
D. Click Save.
E. Click on the Related tab on the record and verify that a new job application is listed
in the Job Applications section.

3. Extra Credit: Create an anonymous block to test bulk data.


A. Add at least 21 candidates using the Execute Anonymous window and verify that the
corresponding job applications are added.

©Copyright 2020 salesforce.com, inc. All rights reserved. 38


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Review

1. What data type is the new attribute on the Trigger class?

2. Why is it important to develop the trigger to handle bulk data from the beginning?

©Copyright 2020 salesforce.com, inc. All rights reserved. 39


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 11-3: Refactoring a Trigger Using a Class

1. Create the JobAppManager class.


A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Class.
C. Enter the name JobAppManager and click OK.
D. Copy the code from the 11-3.JobAppManagerClass.txt file in the Exercises folder
and paste it into the JobAppManager editor window (replacing any default text).
E. Complete the TODO: section as required.
F. Type CTRL+S to save the class.

2. Create the JobAppForCandidate trigger (skip this step if the trigger exists).
A. In the Developer Console, navigate to File | New | Apex Trigger.
B. Enter the following information:
i. Name: JobAppForCandidate
ii. sObject: Candidate__c
C. Click Submit.

3. Call the JobAppManager class from the JobAppForCandidate trigger.


A. If the JobAppForCandidate trigger is not open, open it.
B. Delete any existing code in the trigger.
C. Copy the code from the 11-3.JobAppForCandidateTrigger.txt file in the Exercises
folder and paste it into the JobAppForCandidate editor window (replacing any
default text).
D. Enter the code to call the createJobAppForCandidate on the JobAppManager
class from the JobAppForCandidate trigger.
Note: Make sure the trigger and the class properly handle bulk data.
E. To save the trigger, type CTRL+S.
F. To close all open windows, type CTRL+ALT+/.
G. Close the Developer Console and return to your org.

©Copyright 2020 salesforce.com, inc. All rights reserved. 40


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

4. Create a new candidate to test the trigger and the class.


A. In Salesforce, click the Candidates tab.
B. Click New.
C. Fill out the following fields:
i. First Name: Jim
ii. Last Name: Smith
iii. Gender: Male
iv. Street Address 1: 1234 F St
v. City: Washington
vi. State: DC
vii. Zip: 20008
viii. Country: USA
D. Click Save.
E. Click on the Related tab on the record and verify that a new job application is listed
in the Job Applications section.

Review

1. What is prevented by declaring a List object to store and insert all of the modified
records instead of calling Database.Insert each record inside of the FOR loop?

2. Why is the looping done in the createJobAppForCandidate method and not the
trigger, as in the previous exercise?

©Copyright 2020 salesforce.com, inc. All rights reserved. 41


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 12-1: Debugging Problematic Code

1. Create and add Job Posting Site records.


A. Click the Developer Console from the Gear icon.
B. Type CTRL+E to open the Execute Anonymous Window.
C. Copy the code from the 12-1.ExecuteAnonymous.txt file and paste it into the
Execute Anonymous window. This file contains code that creates 21 Job Posting Site
records and inserts them into the database.
D. Click Execute to execute the code, and then close the Execute Anonymous window.

2. Create the JobPostingManager class.


A. Navigate to File | New | Apex Class.
B. Enter the name JobPostingManager and click OK .
C. Copy the code from the 12-1.JobPostingManagerClass.txt file in the Exercises folder
and paste it into the JobPostingManager editor window (replacing any default text).
D. Type CTRL+S to save the class. Check the errors that appear in the Problems tab.

3. Debug the class.


A. Look over the JobPostingManager class and fix any apparent syntax issues indicated
by the Developer Console.
B. Read through the comments in the code to understand what the original developer
might have intended versus what the code might be doing.
C. Use the query editor to test any SOQL to make sure it returns the appropriate
results.
D. Use the anonymous block window to test the class for any runtime errors.
Note: A few lines of code will need to be written in the anonymous block window to
test this class.
E. Type CTRL+S to save the class.

4. Create the JobPostingFromPositionTrigger trigger.


A. Navigate to File | New | Apex Trigger.
B. Enter the following information:
i. Name: JobPostingFromPositionTrigger
ii. sObject: Position__c
C. Click Submit.
D. Copy the code from the 12-1.JobPostingFromPositionTrigger.txt file in the Exercises
folder and paste it into the Developer Console (replacing any default text)
E. Type CTRL+S to save the trigger. Notice any errors that appear in the Problems tab.

5. Debug the trigger.


A. Look at the JobPostingFromPositionTrigger to make sure it can properly
handle bulk records.

©Copyright 2020 salesforce.com, inc. All rights reserved. 42


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

B. Type CTRL+S to save the trigger.


C. To close all open windows, type CTRL+ALT+/.
D. Close the Developer Console and return to your org.

6. Create a new position to test the trigger and the class.


A. In Salesforce, click the Positions tab.
B. Click New.
C. Select Technical Position and click Next.
D. Fill out the following fields:
i. Title: Java Developer
ii. Status: New
iii. Hiring Manager: Type in Amy and select Amy Lojack.
iv. Job Description: Develop Java-based applications using J2EE
technologies.
E. Click Save.
F. If any errors appear in red at the top, go back to the JobPostingManager class and
JobPostingFromPositionTrigger trigger to see where the issue is occurring.
Note: Consult the Apex Execution Limits slide in Module 11: Trigger Happy for issues
that appear when executing via the UI, but do not appear when executing the class
using an anonymous blocks.
G. If no errors appear, open the Related tab and view the Job Postings List to see if 21
Job Postings have been created.

©Copyright 2020 salesforce.com, inc. All rights reserved. 43


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Review

Consider that JobPostingManager class has the following constructor:

public JobPostingManager() {
//Default constructor does nothing
}

1. If the class was instantiated by this constructor in the


JobPostingFromPostionTrigger trigger, what would occur? What check would need
to be performed in the createJobPosting method to prevent the error caused by a
default constructor that does nothing in its body?

2. What is missing from the code in this exercise that could help you debug the issues?

©Copyright 2020 salesforce.com, inc. All rights reserved. 44


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 12-2: Handling Exceptions

1. Create a custom exception class.


A. In the Salesforce UI, from the Gear icon navigate to Setup | Custom Code | Apex
Classes.
B. Click New.
C. Copy the code from the 12-2.ProgammingLanguageCheckerExceptionClass.txt file
in the Exercises folder and paste it into the Apex Class editor window (replacing any
default text).
D. Complete the TODO sections as required.
E. Click Save.

2. Create the ProgrammingLanguageChecker class, to add the appropriate


try/catch/finally statements.
A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Class.
C. Enter the name ProgrammingLanguageChecker and click OK .
D. Copy the code from the 12-2.ProgrammingLanguageCheckerClass.txt file in the
Exercises folder and paste it into the ProgrammingLanguageChecker editor window
(replacing any default text).
E. Complete the TODO sections as required.
F. To save the class, type CTRL+S.

3. Test the class and the exception using the anonymous block window.
A. Write a few lines of code using the Execute Anonymous window to call each of the
methods in the ProgrammingLanguageChecker class.
Note: Make sure to catch the ProgrammingLanguageCheckerException.
B. To close all open windows, type CTRL+ALT+/.
C. Close the Developer Console and return to your org.

Review

1. When does the finally clause execute?

©Copyright 2020 salesforce.com, inc. All rights reserved. 45


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

2. Which lines will always execute? Assume acct is of type Account.


try {
insert acct;
} catch (Exception e){
System.debug(e.getMessage());
} finally {
return acct;
}

©Copyright 2020 salesforce.com, inc. All rights reserved. 46


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 13-1: Programming a Unit Test

1. Create the JobAppForCandidateTest class.


A. Click the Developer Console from the Gear icon.
B. Navigate to File | New | Apex Class.
C. Enter the name JobAppForCandidateTest.
D. Click OK.
E. Copy the code from the 13-1.JobAppForCandidateTestClass.txt file in the Exercises
folder and paste it into the JobAppForCandidateTest editor window (replacing any
default text).
F. Complete the TODO sections as required.
G. Type CTRL+S to save the class.

2. Run the unit test.


A. Navigate to Test | New Run.
B. Select JobAppForCandidateTest in the Test Classes column, and click > to move it to
the Selected Test Classes column.
C. Click Run.
D. When complete, review the output in the Tests tab at the bottom of the Developer
Console.
i. Expand the code coverage results node and locate the
JobAppForCandidateTest item and confirm test coverage is 100%.
ii. Click the Logs tab, and then double-click the log entry from your test. Review the
system log output and ensure you can identify the output from your debug
statement.

Review

1. Implicitly, what other “code” that was previously created does this test class test?

2. What are three things that can be added to this test to make it a better test?

©Copyright 2020 salesforce.com, inc. All rights reserved. 47


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 14-1: Deploying to Production

1. Authorize your sandbox org to deploy change sets to your production org.
A. Log in to your production org.
B. From the Gear icon, navigate to Setup | Environments | Deploy | Deployment
Settings.
C. Click Continue.
D. In Deployment Connects, click Edit next to the entry for your sandbox org (named
Dev).
E. In the Upload Authorization Direction section, select Allow Inbound Changes.
F. Click Save.
G. Log out of your production organization.

2. Create a change set in your sandbox org.


A. Log in to your sandbox organization.
B. From the Gear icon, navigate to Setup | Environments | Change Sets | Outbound
Change Sets.
C. Click Continue.
D. Click New.
E. Enter the following information:
i. Name: JobAppSet
ii. Description: Contains the JobAppForCandidate trigger, the
JobAppForCandidate Test, and the JobAppManager class.
F. Click Save.
G. In the Change Set Components section, click Add.
H. Choose Apex Class from the Component Type drop-down, then select the following:
i. JobAppManager
ii. JobAppForCandidateTest
I. Click Add To Change Set.
J. In the Change Set Components section, click Add.
K. Choose Apex Trigger from the Component Type drop-down, then select the
following:
i. JobAppForCandidate
L. Click Add to Change Set.

3. Deploy the outbound change set from your sandbox org.


A. In the Change Set Detail section, click Upload.
B. In the Target Organization section, select Production.
C. Click Upload .
D. Log out of your sandbox organization. Note: The time it takes to complete the
upload will depend on the length of the queue at the time requested. You will

©Copyright 2020 salesforce.com, inc. All rights reserved. 48


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

receive an email (sent to the email address specified in your user profile) letting you
know when it has been completed.

4. Accept the inbound change set in your production org.


A. Log into your Salesforce production org.
B. From the Gear icon, navigate to Setup | Environments | Change Sets | Inbound
Change Sets.
C. In the Change Sets Awaiting Deployment section, click JobAppSet.
D. Validate the change set.
i. Click Validate.
ii. Click OK.
iii. Wait a moment, then refresh the page to see the results of the validation.
iv. Confirm that the status is Succeeded.
E. In the Change Set Detail section, click Deploy.
F. Click OK to accept the warning message.

5. Confirm the deployed components are present in your production org.


A. Navigate to Setup | Custom Code | Apex Classes.
B. Confirm the following classes are present:
i. JobAppManager
ii. JobAppForCandidateTest
C. Click Apex Triggers in the Custom Code menu.
D. Confirm the JobAppForCandidate trigger is present.

Review

1. What do change sets allow users to do?

©Copyright 2020 salesforce.com, inc. All rights reserved. 49


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 16-1: Sight-Reading Apex

You have seen this code before at the beginning of class. You will now take this mini-quiz
again to see what kind of progress you have made in your ability to read and understand
Apex code.

Read the code block on the following page. Fill out the worksheet with your guess as to
what is happening on each corresponding line of code.

Note: The code line numbers correspond with the worksheet line numbers.

Review

1. How is the code in lines 1–14 fundamentally different from lines 15–33?

2. What is this code doing?

©Copyright 2020 salesforce.com, inc. All rights reserved. 50


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Code

01 public class Updater{


02 public void updateFirstContact(List<Contact> listOfContacts){
03 if(listOfContacts!= null && (!listOfContacts.isEmpty())){
04 Contact firstContact = listOfContacts.get(0);
05 if(firstContact.id != null){
06 firstContact.firstName += '-updated';
07 firstContact.lastName = firstContact.lastName + '-updated';
08 update firstContact;
09 }
10 } else {
11 System.debug('There are no contacts in the list');
12 }
13 }
14 }

15 Account theAccount = new Account(name = 'My First Account');


16 Database.insert(theAccount);
17 System.debug('The new Account Id is ' + theAccount.id);
18 List<Contact> contactList = new List<Contact>();
19 for(Integer iCounter = 0; iCounter <= 5; iCounter++){
20 Contact oneContact = new Contact();
21 oneContact.accountId = theAccount.id;
22 oneContact.firstName = 'testFirst' + iCounter;
23 oneContact.lastName = 'testLast' + iCounter;
24 contactList.add(oneContact);
25 System.debug('Added to list contact #' + iCounter);
26 }
27 List<Database.SaveResult> saveResults =
Database.insert(contactList);
28 Integer howManyContacts = [SELECT count() FROM Contact
WHERE accountId=:theAccount.id];
29 System.debug('The account has ' + howManyContacts + ' contacts.');
30 System.debug(contactList.get(0));
31 Updater myUpdater = new Updater();
32 myUpdater.updateFirstContact(contactList);
33 System.debug(contactList.get(0));

©Copyright 2020 salesforce.com, inc. All rights reserved. 51


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Worksheet

01 __________________________________________________________________

02 __________________________________________________________________

03 __________________________________________________________________

04 __________________________________________________________________

05 __________________________________________________________________

06 __________________________________________________________________

07 __________________________________________________________________

08 __________________________________________________________________

09 __________________________________________________________________

10 __________________________________________________________________

11 __________________________________________________________________

12 __________________________________________________________________

13 __________________________________________________________________

14 __________________________________________________________________

15 __________________________________________________________________

16 __________________________________________________________________

17 __________________________________________________________________

18 __________________________________________________________________

19 __________________________________________________________________

20 __________________________________________________________________

21 __________________________________________________________________

22 __________________________________________________________________

23 __________________________________________________________________

24 __________________________________________________________________

25 __________________________________________________________________

©Copyright 2020 salesforce.com, inc. All rights reserved. 52


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

26 __________________________________________________________________

27 __________________________________________________________________

28 __________________________________________________________________

29 __________________________________________________________________

30 __________________________________________________________________

31 __________________________________________________________________

32 __________________________________________________________________

33 __________________________________________________________________

©Copyright 2020 salesforce.com, inc. All rights reserved. 53


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Exercise 16-2: Coding the Final Project

Overview Instructions:
There are two versions of the UCAutomate and UCAutomateTest files in the Exercises
folder that will guide you through creating all the code—an easier version and a harder one.
Please copy and paste your desired version into the IDE to help you get started.

Pre-step: Enable Outbound Email in Your Sandbox


1. In your sandbox, navigate to Setup | Email | Deliverability.
2. Set the Access Level dropbox to the All Email option.
3. Save your changes.

Set Up the UCAutomate Class


This class will be responsible for managing the business processes that Universal Containers
would like to automate. If the code that creates Contacts and Reviews resided in triggers,
profile permissions would not be respected since triggers run under the System context.
Likewise, SOQL queries would expose all data even if the sharing model were private.
Another reason for writing your code inside methods of a class is that code in triggers
cannot be reused.

Create the Method createContacts


If you haven’t already done so, copy the code from the file 16-2.UCAutomate.txt, located in
the Exercises folder into your file. At this stage, only implement the createContacts
method. This method accepts a list of Candidates from the trigger and creates a
corresponding Contact for each Candidate. Remember that the method needs to cater
for bulk inserts of Candidates (e.g., using Dataloader).
This method queries the system to check whether existing Contacts contain the email
address of any of the inserted Candidates. If a match is found, it will not create a new
Contact for the Candidate whose email was found to already be in the Contact object.

Create a Trigger on the Candidate Object


In order to fully automate Contact creation, a trigger needs to be developed that will call
UCAutomate class when a Candidate is created. Create a new trigger named
CreateContacts on the Candidate__c object. Instantiate an object of type UCAutomate
And call the createContacts method. Save the classes and the trigger to the server.

©Copyright 2020 salesforce.com, inc. All rights reserved. 54


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Create Candidates
Log in to Salesforce and create two Candidates. Confirm that two corresponding
Contacts were created. Create a third Candidate with an email address that matches an
existing Contact. Confirm that there is no corresponding new Contact created for this
Candidate.

Create the Test Class


For this exercise, a test class will be created to test the createContact method. If you
haven’t already done so, copy the code from the file 16-2.UCAutomateTest.txt, located in
the Exercises folder into your file. At this stage, only implement the
createContactsPositive method. Insert 201 Candidates with unique email addresses
and ensure that there are a corresponding 201 Contact records. Then create a Candidate
with a duplicate email address and ensure that the number of Contacts in the system
does not increase.

The following scenarios should only be completed once all the above steps have been
successfully implemented.

Create the Method createReviews


This method accepts a list of Job Applications from the trigger and creates an
associated Review for each Job Application. Remember that the method needs to cater
for bulk inserts of Job Applications (e.g., using Dataloader).

There are many moving parts involved because of the need to send an email to the
associated Interviewer. There are four objects at play: Job_Application__c, Review__c,
Position__c and Interviewer__c.

The code needs to cater for the fact that a Job Application can be made without
specifying a Position. Furthermore, there may very well be Positions without associated
Interviewers. Such Job Applications are assigned to a generic Interviewer.

Finally, an email message needs to be sent to the Interviewer to inform him/her that a
Review has been created. In order to accomplish this, a pre-existing class will be used.
Copy the code from the file 16-2.Email.txt, located in the Exercises folder, into a new class
named Email. Save the class.

©Copyright 2020 salesforce.com, inc. All rights reserved. 55


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

Create a Trigger on the Job Application Object


In order to fully automate Review creation, a trigger needs to be developed that will call
the UCAutomate class when a Job Application is created. Create a new trigger named
CreateReviews on the Job_Application__c object. Instantiate an object of type
UCAutomate and call the createReviews method. Save the classes and the trigger to the
server.

Upload the Email Class into the org


An email message needs to be sent to the Interviewer to inform him/her that a review
has been created. In order to accomplish this, a pre-existing class will be used. If you have
not already done so, copy the code from the file 16-2.Email.txt, located in the Exercises
folder, into a new class named Email. Save the class.

Create Job Applications


Log in to Salesforce. Ensure that there is at least one Interviewer record where the role is
General. Create a Job Application. Choose an existing Position record for this
application that has an associated Interviewer. Save the Job Application record and
confirm that this record now has a Review record automatically associated to it. The
related Interviewer should have been sent an email (you may wish to provide your own
email address for the Interviewer’s Employee (User) record). Create another Job
Application without specifying a Position. Confirm that a Review record was
automatically associated to it.

Extend the Test Class


Ensure that you test the CreateReviews trigger. The code will need to create a Position
and an Interviewer as well as a Job Application for this purpose.

Further Considerations:
1. The file 16-2.UCAutomateTestHarder.txt contains two test methods that will fail for the
current UCAutomate class. What adjustments can be made to ensure that these
methods execute successfully?

©Copyright 2020 salesforce.com, inc. All rights reserved. 56


Exercise Guide
Introduction to Object-Oriented Programming Using Apex on the Lightning Platform

2. The triggers currently instantiate objects of the UCAutomate class and call methods of
the class using the instantiated object. What considerations should be taken into
account when choosing between this approach and using static methods?

3. The code ensures that a Contact that already contains a new Candidate’s email address
is not duplicated. What changes could be made to the code to cater for many
Candidates being inserted using Dataloader where multiple Candidates share the same
email address?

©Copyright 2020 salesforce.com, inc. All rights reserved. 57

You might also like