Apex Basics & Database Flashcards
As a language, Apex is (9 things):
- Hosted—Apex is saved, compiled, and executed on the server—the Lightning Platform.
- Object oriented—Apex supports classes, interfaces, and inheritance.
- Strongly typed—Apex validates references to objects at compile time.
- Multitenant aware—Because Apex runs in a multitenant platform, it guards closely against runaway code by enforcing limits, which prevent code from monopolizing shared resources.
- Integrated with the database—It is straightforward to access and manipulate records. Apex provides direct access to records and their fields, and provides statements and query languages to manipulate those records.
- Data focused—Apex provides transactional access to the database, allowing you to roll back operations.
- Easy to use—Apex is based on familiar Java idioms.
- Easy to test—Apex provides built-in support for unit test creation, execution, and code coverage. Salesforce ensures that all custom Apex code works as expected by executing all unit tests prior to any platform upgrades.
- Versioned—Custom Apex code can be saved against different versions of the API.
Apex is like other object-oriented programming languages because it supports these language constructs:
- Classes, interfaces, properties, and collections (including arrays).
- Object and array notation.
- Expressions, variables, and constants.
- Conditional statements (if-then-else) and control flow statements (for loops and while loops).
Apex is NOT like other object-oriented programming languages in that it supports:
- Cloud development as Apex is stored, compiled, and executed in the cloud.
- Triggers, which are similar to triggers in database systems.
- Database statements that allow you to make direct database calls and query languages to query and search data.
- Transactions and rollbacks.
- The global access modifier, which is more permissive than the public modifier and allows access across namespaces and applications.
- Versioning of custom code.
Is Apex case-sensitive or case-sensitive?
case-INsensitive
Apex is one data type specific to Salesforce. What is it?
sObject
What data types are supported by Apex?
- A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, Boolean, among others.
- An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c (you’ll learn more about sObjects in a later unit.)
- A collection, including:
- A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections
- A set of primitives
- A map from a primitive to a primitive, sObject, or collection
- A typed list of values, also known as an enum
- User-defined Apex classes
- System-supplied Apex classes
Why is creating a List easier than creating an Array?
Lists don’t require you to determine ahead of time how many elements you need to allocate.
Name a benefit of using Apex classes.
Code reuse. Class methods can be called by triggers and other classes.
Why is Anonymous Apex a handy tool?
Allow you to run lines of code on the fly and is a handy way to invoke Apex, especially to test out functionality. Debug logs are generated as with any other Apex execution.
Before you can insert a Salesforce record, you must …
…create it in memory first as an sObject.
Ex: Account acct = new Account();
How many ways can you add fields to an sObject, and what does the syntax look like?
1. through a constructor Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);
2. using dot notation Account acct = new Account(); acct.Name = 'Acme'; acct.Phone = '(415)555-1212'; acct.NumberOfEmployees = 100;
Is dot notation available when working with a generic sObject?
No, because a generic sObject doesn’t know what it is, so there are no properties accessible.
But, you can cast the generic sObject as a specific sObject to access its properties, e.g.:
// Cast a generic sObject to an Account
Account acct = (Account)myGenericSObject;
// Now, you can use the dot notation to access fields on Account
String name = acct.Name;
String phone = acct.Phone;
Describe how creating generic sObjects is different from creating specific sObjects.
Generic sObjects can only be created through the newSObject() method. Also, the fields can only be accessed through the put() and get() methods.
To retrieve a record, you have to use what?
SOQL - Salesforce Object Query Language
To insert an sObject as a record, you have to use what?
DML - Data Manipulation Language
What does DML provide?
Straightforward way to manage records by providing simple statements to insert, update, merge, delete and restore (undelete) records.
How is Apex DML different from other programming languages?
Other programming languages require additional setup to connect to data sources, but Apex DML allows quick access to perform operations on SF records because Apex is data focused.
What does the “merge” DML statement do?
Merges up to 3 records of the same sObject into one record, Deletes the others, and re-parents any related records.
How would you retrieve the ID of a newly created record in Salesforce?
On insert, the ID is automatically returned to the sObject variable used for insert, so it’s immediately accessible.
What is the max number of DML statements per Apex transaction?
150
If you don’t specify a field when doing an “upsert” statement, what field is used by default?
The sObject’s Id.
What fields can be used during an “upsert” statement to identify records?
For custom objects, the Id field or any other field marked as an external ID.
For standard objects, the Id field and any field that has idLookup property set to True. For example, Email on both Contact and User objects has this property set.
upsert sObjectList Account.Fields.MyExternalId;
What happens if multiple matching records are found during an “upsert” statement?
An error is generated and the object record is neither inserted or updated.
How many days does a deleted record live in the Recycle Bin?
15 days
What is returned when a DML operation fails?
An exception of type DMLException.
You can catch exceptions in your code to handle error conditions.
try { // This causes an exception because // the required Name field is not provided. Account acct = new Account(); // Insert the account insert acct; } catch (DmlException e) { System.debug('A DML exception has occurred: ' + e.getMessage()); }
What are the available built-in Database class methods?
- Database.insert()
- Database.update()
- Database.upsert()
- Database.delete()
- Database.undelete()
- Database.merge()
How are the Database methods different from their DML counterparts?
Database methods have an optional allOrNone parameter that allows you to specify whether the operation should partially succeed.
Also, the Database class contains methods that aren’t provided as DML statements.
- Transaction control and rollback
- Emptying the Recycle Bin
- and methods related to SOQL queries
What happens if the allOrNone parameter is set to False in a Database method?
If errors occur on a partial set of records, the successful records will be committed and errors will be returned for the failed records. Also, no exceptions will be thrown with the partial success option.
What happens if the allOrNone parameter is set to True in a Database method?
An exception will be thrown if a failure is encountered and none of the records will be successfully saved.
What is the default value of the allOrNone parameter on Database methods?
True
What is returned when using each of the Database methods?
For create and update, Database.SaveResult.
For upsert, Database.UpsertResult.
For delete, Database,DeleteResult.
What is the syntax for saving something to the Debug log?
System.debug(‘Text to enter into log’ + variable);
Why would you use DML over a Database method?
If you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control by using try…catch blocks. This behavior is similar to the way exceptions are handled in most database procedural languages.
Why would you use Database methods over DML?
If you want to allow partial success of a bulk DML operation. If you want to inspect the rejected records and possibly retry the operation. If you want to avoid thrown exceptions and instead take action on successes and failures differently and intentionally.
Can you insert records related to existing records?
Yes, if a relationship has already been defined between the two objects, such as lookup or master-detail lookup relationship.
Account acct = new Account(Name='SFDC Account'); insert acct; // Once the account is inserted, the sObject will be // populated with an ID. // Get this ID. ID acctID = acct.ID; // Add a contact to this account. Contact mario = new Contact( FirstName='Mario', LastName='Ruiz', Phone='415.555.1212', AccountId=acctID); insert mario
Can you delete a parent object and its children (cascading deletes) automatically in one DML statement operation?
Yes, as long as each child record can be deleted.
Account[] queriedAccounts = [SELECT Id FROM Account WHERE Name=’SFDC Account’];
delete queriedAccounts;
DML operations execute within a ____.
transaction
What happens when a DML operation fails?
DML operations execute within a transaction, so if an error occurs during one operation, the entire transaction is rolled back and no data is committed to the database.
What are the boundaries of a transaction?
A trigger, a class method, an anonymous block of code, an Apex page, or a custom Web service method.
For example, if a trigger or class creates two accounts and updates one contact, and the contact update fails because of a validation rule failure, the entire transaction rolls back and none of the accounts are persisted in Salesforce.
When SOQL is embedded in Apex, it is referred to as ____.
inline SOQL
Can you do a “SELECT *” in SOQL?
No, which is dumb.
Do you have to specify the Id field in a SOQL query?
No, if more fields are being retrieved. If Id is the only field you’re trying to retrieve, then Yes, you have to specify it.
What is the syntax for using a variable within a SOQL statement?
Field=:variable
e.g.
String targetDepartment = ‘Wingo’;
Contact[] techContacts = [SELECT FirstName,LastName
FROM Contact WHERE Department=:targetDepartment];
How can you retrieve child records related to a parent record in a SOQL query?
Use an inner query for the child records. The FROM clause of the inner query runs against the relationship name, rather than a Salesforce object name.
e.g.
SELECT Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = ‘SFDC Computing’
e.g. accessing the related records in Apex:
Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts)
FROM Account
WHERE Name = ‘SFDC Computing’];
// Get child records
Contact[] cts = acctsWithContacts[0].Contacts;
System.debug(‘Name of first associated contact: ‘
+ cts[0].FirstName + ‘, ‘ + cts[0].LastName);
What happens when using SOQL in a “for” loop?
Records are retrieved using efficient chunking with calls to the query and queryMore methods of the SOAP API. By using SOQL for loops, you can avoid hitting the heap size limit. SOQL for loops iterate overall of the sObject records returned by a SOQL query.
e.g. The syntax is either:
for (variable : [soql_query]) {
code_block
}
OR
for (variable_list : [soql_query]) {
code_block
}
Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query.
It is preferable to use the sObject list format of the SOQL for loop as the loop executes once for each batch of 200 sObjects. Doing so enables you to work on batches of records and perform DML operations in batch, which helps avoid reaching governor limits.
What is an unordered collection of elements that does not contain duplicates and is therefore often used to store ID values since they are always unique?
Set
What is an ordered collection of elements that work similar to a traditional array?
List
What is a collection of key-value pairs?
Map
Visualforce is…
…a framework for rendering HTML pages using an MVC platform.
How much test coverage must you have to deploy your code to a production org?
75%
For ASP.NET applications, code is executed in the context of an application domain. In the Lightning Platform world, code executes within an…
…execution context.
Defined as the time when the code starts to execute to the time it finishes. The Apex code you write is not always the only code that is executing.
What are the 6 ways that Apex can be invoked?
- Database Trigger
- Anonymous Apex
- Asynchronous Apex
- Web Services
- Email Services
- Visualforce or Lightning Pages
Describe how Database Triggers are invoked.
Invoked for a specific event on a custom or standard object.
Describe how Anonymous Apex is invoked.
Code snippets executed on the fly in Dev Console or other tools.
Describe how Asynchronous Apex is invoked.
Occurs when executing a future or queueable Apex, running a batch job, or scheduling Apex to run at a specified interval.
Describe how Web Services are invoked.
Code that is exposed via SOAP or REST web services.
Describe how Email Services are invoked.
Code that is setup to process inbound email.
Describe how Visualforce or Lightning Pages are invoked.
Visualforce controllers and Lightning components can execute Apex code automatically or when a user initiates an action, such as clicking a button. Lightning components can also be executed by Lightning processes and flows.
When do Triggers execute?
Before or after database actions:
- before insert, update or delete
- after insert, update, delete or undelete
What are the two limits you will probably be most concerned with?
Number of SOQL queries and DML statements.
What should always be at the top of test classes?
@isTest
What are three reasons to use Asynchronous programming?
- Processing a very large number of records
- Making callouts to external web services
- Creating a better and faster user experience
How must future methods be declared?
As static void. They cannot return anything.
True or False: You cannot pass objects as arguments into future methods.
True
What are three drawbacks to using future methods?
- You can’t track execution because no Apex job ID is returned.
- Parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. Future methods can’t take objects as arguments.
- You can’t chain future methods and have one call another.
What are the different types of Asynchronous Apex?
- Future Methods
- Batch or Scheduled Apex
- Queueable Apex
What are three drawbacks to using batch or scheduled apex/the batchable interface?
- Troubleshooting can be troublesome.
- Jobs are queued and subject to server availability, which can sometimes take longer than anticipated.
- Have we talked about limits yet?
Queuable Apex provides what benefits to future methods?
- Non-primitive types. Classes can accept parameter variables of non-primitive data types, such as sObjects or custom Apex types.
- Monitoring - When you submit your job, a jobId is returned that you can use to identify the job and monitor its progress.
- Chaining jobs - You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful for sequential processing.
What is the Apex Flex Queue?
Eliminated limitation of five concurrent batches in 2015 and allows developers to monitor and manage the order of queued jobs.
What are all of the debug logging levels?
NONE ERROR WARN INFO DEBUG FINE FINER FINEST
Debug logs cannot be larger than ____.
2 MB
Each org can retain up to ____ in debug logs.
50 MB
What are the ways you can add VisualForce to your org?
- Open a VF page from the App Launcher
- Add a VF page to the Navigation bar
- Display a VF page within a Standard Page Layout
- Add a VF page as a Component in the Lightning App Builder
- Launch a VF page as a Quick Action
- Display a VF page by overriding Standard Buttons or Links
- Display a VF page using Custom Buttons or Links
To make a VF page available in the Lightning App Builder, you must enable…
“Available for Lightning Experience, Lightning Communities, and the mobile app”
What are VisualForce Expressions?
Global variables, calculations and properties made available by the page’s controller. Use them for dynamic output or passing values into components by assigning them to attributes.
A VisualForce expression is …
…any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value.
True or False: Method calls are allowed in VF expressions.
False
What is VF Expression syntax?
{! expression}
VF Expressions are case sensitive or insensitive?
Case IN-sensitive
How many built-in components are available in VisualForce?
nearly 150
What do coarse-grained components allow you to do?
Quickly add lots of functionality to a page
What do fine-grained components allow you to do?
Give you more control over specific details of a page.
What does a Standard List Controller do?
Allows you to create VisualForce pages that can display or act on a set of records.
Provides many powerful, automatic behaviors such as querying for records of a specific object and making the records available in a collection variable, as well as filtering and pagination through the results.
What are static resources?
Static resources allow you to upload content that you can reference in a Visualforce page. Resources can be archives (such as .zip and .jar files), images, stylesheets, JavaScript, and other files.
What does CDN stand for?
Content Distribution Network
What are custom controllers?
Contain custom logic and data manipulation that can be used by a VF page. For example, a custom controller can retrieve a list of items to be displayed, make a callout to an external web service, validate and insert data, and more—and all of these operations will be available to the Visualforce page that uses it as a controller.
When would you choose to use a custom controller instead of a standard controller?
When you want to override existing functionality, customize the navigation through an application, use callouts or Web services, or if you need finer control for how information is accessed for your page, Visualforce lets you take the reigns
Can you use a custom controller and a standard controller together at the same time?
No
An alternative to getters and setters is to use ____.
Apex properties
public MyObject__c myVariable { get; set; }
What are packages?
Containers for apps, tabs, and objects installed into your org from the AppExchange
What flavors do packages come in?
Managed and Unmanaged
Describe the differences between Managed and Unmanaged packages.
- You can’t view or change the offering’s code or metadata in a Managed package, but you can in an Unmanaged package.
- The provider automatically upgrades Managed packages, but with Unmanaged packages, you have to download and reinstall the latest version manually.
- The contents of the package DO count against your app, tab, and object limits if Unmanaged but don’t count against them with a Managed package.
What is the AppExchange product lifecycle?
roadmap to everything from ensuring that you’re building the right product to supporting the product after it’s launched. Stages are: Plan, Build, Distribute, Market, Sell, and Support.
What is the Lightning Component Framework
A UI development framework similar to Angular JS and React
What is Apex?
Salesforce’s proprietary programming language with Java-like syntax
What is VisualForce?
A markup language that lets you create custom Salesforce pages with code that looks a lot like HTML, and optionally can use a powerful combination of JavaScript and Apex.
What types of elements do you see in the XML markup for Lightning components?
Static HTML tags and Lightning component tags
What’s one situation where it’s better to use Lightning Components instead of Visualforce?
Mobile apps
What is multitenancy?
All customers share the same infrastructure and run on the same platform.
What is returned when doing an aggregate SOQL query? (Most aggregate functions)
List
Are JOINs supported in SOQL queries?
No
What does a SOSL nickname search apply to?
English-based searches on Account, Contact, Lead, and User
What does the Query Optimizer do?
Evaluates SOQL queries and SOSL searches. It routes queries to the appropriate indexes. Looks at every incoming query and assigns it a cost value for each potential query path that it identifies. Then uses costs to determine which execution plan to use.
Fields that are automatically indexed include:
Id, Name, OwnerId, CreatedDate, SystemModStamp, Record Type, Master-Detail Fields, Lookup Fields, Unique Fields, and Exernal Id fields
Avoid these types of queries:
Querying for null rows
Negative filter operators
Leading wildcards
Text fields with comparison operators
Query Plan tool - can you use it with SOSL?
No, just SOQL
Included in Lightning Flow are two point-and-click automation tools: Process Builder, which lets you build processes, and Cloud Flow Designer, which lets you build flows.
To sum up the differences:
Lightning Flow is the name of the product.
Process Builder and Cloud Flow Designer are the names of the tools.
Use Process Builder to make processes; use Cloud Flow Designer to make flows.
Use Process Builder when you need to start a behind-the-scenes business process automatically. Processes can start when:
A record is created
A record is updated
A platform event occurs
Use Cloud Flow Designer to:
Automate a guided visual experience.
Add more functionality for a behind-the-scenes process than is available in Process Builder. Build the more complex functionality in the Cloud Flow Designer. Then call the resulting flow from the process.
Start a behind-the-scenes business process when a user clicks something, like a button.
Use Apex when
you need more functionality than is available in Process Builder or Cloud Flow Designer. Build the more complex functionality as invocable Apex methods. Then call the resulting Apex as an Apex action in the process or as an Apex element in the flow.
Every process consists of
a trigger, at least one criteria node, and at least one action
Process Builder is
a point-and-click tool that lets you easily automate if/then business processes and see a graphical representation of your process as you build.
A PB can be triggered by one of 2 events:
Only when a record is created
Anytime a record is created or edited
In PB, how many criteria can you set up?
As many as your heart desires
In PB, in each criteria node, you can:
Set filter conditions.
Enter a custom formula. Like in validation rules, the formula must resolve to true or false.
Opt out of criteria and always execute the associated actions.
In PB, with scheduled actions, you can schedule actions based on either:
A specific date/time field on the record that started the process.
For example, a month before an account’s service contract expires.
The time that the process ran.
For example, 3 days from now.
In a scheduled action, at the specified time, Salesforce does what?
makes sure that the associated criteria node still evaluates to True
In PB, these are actions you can configure:
Create records.
Update the record that started the process or any related record.
Submit that record for approval.
Update one or more related records.
Send emails using a specified email template.
Post to a Chatter feed.
Process Builder can automate a few kinds of business processes. The main difference is the trigger: when the process starts.
Type Process Starts When
Record Change A record is created or edited
Invocable It’s called by another process
Platform Event A platform event message is received
Process Builder can’t:
Post to a community feed Submit a related record for approval Delete records Create a bunch of records and associate them with each other Perform complex logic
Flow variables come in 4 types:
Variable A single value “Hello World”, true, 6
sObject Variable A set of field values for a single record Rating, ID, and Name for an account
Collection Variable Multiple values of the same data type [1, 2, 3, 5, 8, 13]
sObject Collection Variable A set of field values for multiple records that have the same object Rating, ID, and Name for multiple accounts