SalesforceBen PD1 Practice Exam Question Review
These are technical notes I compiled while studying using a free practice exam hosted on salesforceben.com.
- You have an
@AuraEnabled
method which accepts an SObject from a Lightning Component which will be inserted. How can you easily sanitise the user’s input
Use theSecurity.stripInaccessible()
method
The Security class methods are designed explicitly for easily enforcing the FLS of the current user by stripping anything which is not accessible in the defined context. While checking each field’s accessibility using the DescribeSObjectResult for the SObject is a valid approach, it is far more verbose and requires a lot more code to achieve the same results as utilising theSecurity.stripInaccessible()
methods. - How can a developer declaratively access a specific custom metadata type (
MyCustomMetadataType__mdt
) record within Apex?
MyCustomMetadataType__mdt.getInstance('Record_Name')
Each custom metadata type comes with its own SObject type in Apex. This type contains additional methods which can be used to declaratively obtain records from a custom metadata type by developer name or record Id. These methods are similar to those found on custom settings. - How can a developer schedule an Apex job?
Use the Apex Scheduler
Use theSystem.schedule()
method within Apex
Apex jobs can be scheduled in the UI via the Apex Scheduler or through writing a line of code to enqueue the job via code (e.g., submitting via the Developer Console). TheSystem.enqueJob()
method is not used for scheduled jobs and is instead used to queue a queueable piece of apex, the main difference being queueable apex executes at the soonest possible time, whereas a scheduled job executes at the designated time. - A developer wishes to iterate over a list of records returned from a query, which of the following loop types is most appropriate?
SOQL for loop
SOQL for loops differ from a traditional for loop, or a List/Set for loop in that they can utilise more efficient chunking of SObjects behind the scenes, resulting in a reduced heap usage and a lower chance of hitting governor limits for large queries. This type of loop should be the tool of choice when iterating over query results as it can mitigate the chance of hitting errors as a dataset scales. - Which of the following code snippets correctly defines a new custom exception?
public class MyCustomException extends Exception{}
A custom exception is a class (either inner or top level) which extends the built in Exception class. The only restriction is that the class name ends with “Exception” however, there are no other limitations around the custom class, that is they can have their own methods, constructors, or member variables as required. - A developer wishes to add a picklist to a Lightning Web Component they are building. Which of the following snippets should they use?
<lightning-combobox></lightning-combobox>
The LWC framework follows the HTML specification for how it expects HTML to be written within component templates. This means that for any components that aren’t base HTML tags, it is required that no component tags are self-closing (i.e., there is always an explicit closing tag). In LWC, when we wish to display picklists, we should utilise the base component called combobox. In Aura, we can either use the combobox or the select components, however in LWC we only have the combobox as there is no lightning-select component. - What would the value of the instance variable “foo” be after the third execution of the following batch class?
4
The instance variable is initially initialised as 1 during the constructor of the batch class. This is then incremented by 1 for each execute method run. Since this batch class also implementsDatabase.Stateful
,the instance variables of this class are preserved after each execute method call, hence why the output value is 4.
public with sharing class ExampleClass implements Database.Batchable<SObject>, Database.Stateful {
private Integer foo;
public ExampleClass() {
this.foo = 1;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Contact');
}
public void execute(Database.BatchableContext bc, List<SObject> scope) {
this.foo = foo++;
}
public void finish(Database.BatchableContext bc) {}
}
- You have been tasked with creating a process which sends a very large number of emails to Contacts within an Org, how best could this be achieved?
Install an AppExchange app
For a complex task such as this, the first step should be investigating whether there has been an app released on the AppExchange which fits your use case. If there are no suitable AppExchange apps, only then should custom development be considered. - A custom field on Opportunity is assigned the number data type, with 18 digits and 0 decimal places. Which primitive data type would this be assigned in Apex?
Double
All data stored within a number field (or number returning formula) is represented as a Double when accessed within Apex. - What data types can a SOQL query return?
List<SObject
SObject
Integer
The SOQL engine within Apex is incredibly flexible in how we can call it, and how it returns data for us to consume with the code. The most common return type is a List, this will be when a simple query is run. The SObject return type can be used when a query is known to return a single record only, for example when using a LIMIT 1 or querying for a specific ID. The integer return type is used when we use the COUNT query function. - You have been tasked with writing a utility class which can be called from multiple contexts, for example while running as an Experience User and an internal user who should see all records. Which sharing declaration should be used in your class to facilitate this?
Inherited Sharing
There are three sharing keywords available in Apex, With, Without and Inherited. With and Without sharing explicitly run a class with or without sharing enforced. The third, Inherited, is a little different; Inherited sharing takes on the sharing declaration of the class which has executed the code, so if a class with sharing enforced calls a method in a class with inherited sharing, the inherited sharing class code would run with sharing enforced. This is really useful for when the sharing model to be used isn’t known at design time, or the code is built to be called from varying places within the system. - Which of the following statements is true about sharing keywords of Apex classes?
Inner classes do not inherit the sharing mode from the outer class
Inner classes can have their own sharing modes declared, which don’t have to match that of the outer classes. This can be useful for nesting specific methods which require without sharing inside a class which has with sharing declared. - What is the result if the following trigger is executed for 50 records?
A runtime exception is thrown
The variables which are present within a Trigger are dependent on the current trigger context. In this case we are operating in a Before Insert context, this means the record hasn’t been inserted into the database yet and so there can be no old value for the record, and so the Trigger will throw a null pointer exception on line 2.
trigger Test on Opportunity (before insert) {
Opportunity newOpp = Trigger.new[0];
Opportunity oldOpp = Trigger.oldMap.get(newOpp.Id);
if(newOpp.Amount != oldOpp.Amount) {
newOpp.MyField__c = true;
}
}
- Which of the following method signatures allows an Apex method to be used by the wire service?
@AuraEnabled(cacheable=true) public static Object performAction()
The Wire service is designed to provision a component with an immutable stream of data to a component that is ever updating. Because of this, the values returned by the Apex methods must be cached and so we must always annotate a method intended to be used by the Wire service with@AuraEnabled(cacheable = true)
. - What would be the result of executing the following Apex test?
A “List has no rows for assignment to SObject” error would be thrown
When running a query which returns no rows, a “List has no rows for assignment to SObject” error will be thrown. An index out of bounds error would not be thrown in this scenario since we are not directly trying to access an element from an array.
@isTest
public class ExampleTest {
@isTest
static void test() {
Contact testContact = [SELECT Id FROM Contact LIMIT 1];
System.assert(testContact != null);
}
}
- You have been tasked with importing data from a legacy CRM system into a new Salesforce org. The legacy CRM system had database tables analogous to the Account, Contact and Opportunity objects within Salesforce. How could you best ensure the relationships are preserved during this data migration?
Add fields flagged as external Ids for each of the objects to be imported, populated with its legacy CRM Id, use the Data Loader tool, and set the relationship fields to match these external Ids
External Ids allow flagging a field as an Id which is used within an external system. This allows the field to be utilised in Upsert calls, where instead of specifying the Salesforce Id for a relationship field, the external Id can be used instead. The external Id is then used to find the record within Salesforce and the relationship field value gets replaced with its Salesforce Id instead. This type of operation is supported by the Data Loader tool. Utilising manual methods of doing this match introduces the risk of human error when re- establishing the relationships. - Which of the following uses the correct naming convention to be used for naming CustomEvent fired from Lightning Web Components using dispatch event?
my_action
The naming scheme for events within Lightning Web Components follows the DOM event standard. This means that all event names must not use uppercase letters, have no spaces, and use underscores to separate words. - A Lead has been converted to a Contact and Account, which triggers are fired?
Triggers on Lead, Contact and Account
Lead conversion causes Apex triggers to fire, the scope of which depends on the records the Lead is being converted to, but at a bare minimum the triggers on the Lead object are fired. If a Lead is creating or updating any secondary objects, those objects also have their triggers fired. - As a developer you wish to build a reusable Lightning Web Component which can be used to
search records and to select one. Which snippet can this component alert its parent component
to the selected record?
this.dispatchEvent(new CustomEvent(“my_event”, {detail: this.recordId}))
Lightning Web Components utilise the standard CustomEvent class within JavaScript, which is then dispatched through the EventTarget.dispatchEvent() method, which in the majority of cases, would be this.dispatchEvent() – since we would want parent components to handle this event. We add information to the event with the detail property of CustomEvent, which the event handlers can access and process accordingly. The detail property can be any datatype. We should follow the DOM event standard in the naming of our events, meaning no upper-case letters, no spaces, and underscores to separate words. - Which of the following snippets can be used to obtain the Stage picklist values on the Opportunity object?
Opportunity.StageName.getDescribe().getPicklistValues();
To access field metadata within Apex we use the FieldDescribeResult for the field we are interested in, this can be accessed declaratively as in the answer to this question, or programmatically as shown below. We access the picklist values of a field by calling the getPicklistValues() method on it’s describe result, this returns us a List of PicklistEntry which we can use as desired. - What are the valid target source pairs for a changeset deployment?
Sandbox – Sandbox
Sandbox – Production Org
Changesets are only available within a production org and its sandboxes. The purpose of them is to allow development and testing to be done in a metadata clone of a production org, and for those changes to be migrated into production when ready. Since developer orgs are not tied to a production instance and are instead standalone, they do not feature changesets and so cannot be the target nor the source of a changeset deployment - How can a developer execute an anonymous block of Apex code?
Use the “Execute Anonymous” functionality of the Developer Console
Utilise the REST API “executeAnonymous” endpoint
Use the Salesforce CLI “force:apex:execute” command
Anonymous Apex code can be executed both on platform and off platform. On platform this is done directly in the Developer Console, utilising the Developer Console’s inbuilt functionality. When we wish to run code off platform, there are several ways this can be achieved. One of the easiest is to utilise the Salesforce CLI commands, as these can run code directly from either a terminal, or from code stored within a file. Lastly we can utilise either the SOAP or the REST APIs to send code to Salesforce to be executed. - A developer has an @AuraEnabled method that is frequently used in several Lightning Web
Components. It performs some complex calculations based on data stored within custom metadata. Unless these values change, this method will always return the same result. How can the developer improve the runtime performance of Lightning Components utilising this method?
Modify the method to be@AuraEnabled(cacheable=true)
When we wish to flag an Apex method as cacheable, so the result should be cached client side, we must modify our Apex method to indicate so. We do this by adding the “cacheable = true” parameter to the @AuraEnabled annotation. The setStorable method must be used if we wish for an Apex action to be cached within an Aura component, however there is no such requirement when we are working with LWCs. - Which of the following statements are true about formula fields?
Formulas are calculated at access time
Formulas can span multiple objects
Formula fields are special fields within Salesforce, regardless of how they are accessed, their value is only calculated when they are accessed. If they are accessed within Apex or a Flow, this may be the first time they are accessed, such as when the field was queried. However, in Apex these values can be requested to be recalculated.
Fields referenced within a formula can reference other objects by using relationship spanning fields, i.e. referencing the Account Name from a formula on Contact would be done using “Account.Name”.
Formula fields have a compile time maximum character limit of 3900 characters, this limit can be extended by referencing other formulas, however there is a compile time maximum limit on the size of the formula (5000 bytes), which considers other formula field’s size. - What is the maximum number of records that can be processed by a trigger at a time?
200
The maximum number of records processed by a trigger at a time is 200. If the number of records being inserted is greater than this (e.g. from the Bulk API or a bulk DML operation), the trigger is invoked in batches of 200 records at a time. - You are working for a server installation provider and have been requested that whenever an
Opportunity is created with a value over £10000 to enforce that there has been a Site Review
record created before allowing the Opportunity stage to be set to Closed Won. How best can this
be achieved?
Use an Apex trigger and use the addError() method if the criteria hasn’t been met
Standard validation rules are unable to operate on parent child relationships so Apex validation is required instead. Apex validation allows complex validation logic to be performed on record save operations. This is done by processing the records for the required criteria, and then calling the addError() method on each individual method with the validation message a user should see as an argument for the method. - A developer creates an Apex trigger which calls a method within another class. A test has been
written which directly calls the method within the class and provides 100% code coverage. There
are no other Apex classes present within the org. What would be the result of deploying a
changeset with this trigger and classes into production with running all tests?
The deployment fails because the Apex trigger has 0% code coverage
When doing a deployment into production, there must be an average of 75% code coverage for all Apex code within the org. Alongside this, Apex triggers being deployed must have at least 1 line being covered (i.e. they must have been called by at least one test class). When running deployments, there is the option to run a subset of tests which changes the code coverage behavior. When running the default testing mode, all tests are executed and the total coverage in an org must meet 75%. However, when running a specified set of tests, every item in the deployment must average 75% instead. - How can data for a record be easily accessed in Lightning Components?
Utilise the Lightning Data Service
When building components that work on individual records, the Lightning Data Service provides a performant and cached mechanism for loading and updating record data that gets propagated throughout all components utilising the service. This offers advantages over performing Apex calls to achieve simple record data since it increases performance and allows changes in other areas of the UI (for example for the standard record details component) to propagate to other components. - What is the value of “foo” after this following code has been executed?
30
Switch statements allow a developer to test whether an expression matches one of several different values in a branch, and perform some code based on the matching branch. In the question, the switch operation compares an Enum value against several options. Since the value operation is AFTER_INSERT, the switch statement evaluates each branch until it matches the AFTER_INSERT value, which executes the code block, which sets foo to equal 30.
Integer foo = 0;
System.TriggerOperation operation = System.TriggerOperation.AFTER_INSERT;
switch on operation {
when BEFORE_INSERT{
foo = 10;
}
when AFTER_INSERT {
foo = 30;
}
when BEFORE_UPDATE {
foo = 20;
}
when AFTER_UPDATE {
foo = 10;
}
when else {
foo = 40;
}
}
- How can Apex classes be deleted from production instances?
Use the Metadata API with a tool such as ANT
Apex classes and some other metadata cannot be directly deleted from production. While these pieces of metadata can be deleted within a Sandbox, changesets cannot upload these destructive changes. Instead the Metadata API must be used. This could be with a tool such as ANT to produce a destructive changeset which is deployed into the org. - As a developer you have been tasked with creating a simple record form to create Cases on a
private community page, how could you best achieve this?
Use a Lightning Component with a Lightning Record Form to display the form
To easily create record forms, a lightning-record-form component is the best choice. This component can be used to rapidly create forms based on a list of fields or layouts for an object choice, which can allow admins to maintain the forms without requiring developer intervention. - What is the primary purpose of creating test classes in Apex?
Test that the logic within a class is behaving as expected
Test classes within Salesforce play a very important role: they are used to determine whether a piece of code is behaving exactly as it was intended to. Properly written tests can act as early warning signs for when things go wrong, and can help easily identify specific pieces of code that are no longer behaving as expected (for example, due to conflicting with a recently introduced Process Builder or Flow). - You are tasked with creating a Lightning Component which will allow a user to search public
records of an object by filtering multiple field values. What can be done to ensure this component
can be securely used?
Sanitise any user input
Add the “WITH SECURITY_ENFORCED” clause to the query
Use bind variables for user input
Hardcode the filterable fields in the Apex controller
Utilise the “with sharing” keyword on the Apex class
Any area where user input is used to query data within the database should be considered an avenue for attack and should be protected against.
Sanitising the user input protects against SOQL injection by ensuring values are treated as values and not accidently interpreted as extensions to a query. This is easily achieved with bind variables.
The “WITH SECURITY_ENFORCED” clause of a query prompts the SOQL engine to enforce permissions on the query, so if a query attempts to access a field or object the user doesn’t have access to, an exception is thrown.
A piece of Apex should never trust search parameters from a Lightning Component as these could easily be manipulated. Instead, in scenarios where this is required, alternative approaches should be used such as hardcoding the filter variables in an Apex datatype or as parameters to the method, in order to ensure that any requested fields/filters have been explicitly pre authorised. - What are the use cases for the Test.startTest() and Test.stopTest() methods when used within a
test class?
Indicate your test code is executing and to assign it a new set of governor limits
Force asynchronous code the execute synchronously on calling Test.stopTest()
Test classes come in three distinct parts: 1. Setup – preparing data and the runtime environment for your testing scenario 2. Execution – executing the code you wish to test 3. Validation – verifying the results of the executed test against the expected results The process of setting up and preparing a test can result in the consumption of many governor limits before the actual code we wish to validate has been run, for example having to insert Accounts if you wish to validate a rollup from Opportunity.
This is not an ideal scenario as it causes our test execution to potentially not run in a realistic environment. We can use the Test.startTest() method just before executing the code we wish to test to assign that block of code a new set of governor limits. We can then call Test.startTest() once we’ve finished our execution and are ready to validate our results. - A developer has many records which must be displayed on a Visualforce page, how can they
best add pagination?
Utilise the StandardSetController built in methods
The StandardSetController is designed to work with sets of records, and so provides built in methods to enable a large set of records to be displayed on a Visualforce page, with methods to assist in pagination of the record list.