Tuesday, 27 December 2022

Dynamically Pass Bind Variables to a SOQL Query (Spring 23)

 New Database.queryWithBinds, Database.getQueryLocatorWithBinds, and Database.countQueryWithBinds methods, the bind variables in the query are resolved from a Map parameter directly with a key rather than from Apex code variables.

ex :

Map<String, Object> acctBinds = new Map<String, Object>{'acctName' => 'Acme Corporation'};

List<Account> accts = Database.queryWithBinds('SELECT Id FROM Account WHERE Name = :acctName',  acctBinds,   AccessLevel.USER_MODE);


Wednesday, 14 December 2022

Salesforce Flow elements

 1 Create = 1 DML

1 GET = 1 SOQL


1 Update without filter criteria = 1 DML

1 Update with filter criteria = 1 DML + 1 SOQL


1 Delete without filter criteria = 1 DML

1 Delete with filter criteria = 1 DML + 1 SOQL


Statements above count towards flow limits, let's be mindful of them


PS: the criteria in update and delete is like using a get element in the update or the delete.

If you use filter criteria in Update Records or Delete Records is will use a query.

object and field level security check in Apex

 "With Sharing" does not enforce object level and field level by default.


But there are other ways in which you can enforce them.


Here are couple of options:


1. While using an SOQL use "WITH SECURITY_ENFORCED" keyword to enforce field- and object-level security checks to fields and objects referenced in SELECT.


2. In Apex code, you can use sObject describe result methods and field describe result methods that check current user's permission. Methods are isAccessible, isCreateable, isUpdateable and isDeletable.


3. Use the stripInaccessible method to enforce field- and object-level data protection.


Sunday, 11 December 2022

Apex CPU Time Limit

 Usually, all the developers came across this term while developing some complex logic in apex. Apex has System.LimitExceptions and "Apex CPU time limit exceeded" is one of them.


Apex CPU time limits:

1] Synchronous Limit - 10,000 milliseconds (10 Seconds)

2] Asynchronous Limit - 60,000 milliseconds (60 Seconds)


To resolve this exception we can follow below points:


1] Avoid Multiple automation on a Single Object

2] Trigger Framework

3] Avoid multiple Validation Rules

4] Using Map based query

5] Use Async Apex (Future, Batch, Queueable, Schedulable)

6] Aggregate SOQL usage

7] Avoid Nested For loop

8] Avoid using process builder

9] Use Return Early Pattern


What is not counted for Apex CPU Time Limit?


1] Database operations like database operation for DML, SOQL and SOSL.

2] Wait time for Apex Callout

3] Aggregate SOQL


Sunday, 20 November 2022

Apex offers two ways to perform DML operations

Apex offers two ways to perform DML operations:


1. DML statements :


Eg : Insert Acc ;


This is more straightforward to use and result in exceptions that you can handle in your code.


2. Database class methods :


Eg: Database.insert(Acc, false);


By using the Database class method, you can specify whether or not to allow for partial record processing if errors are encountered. If you specify false for the second parameter and if a record fails, the remainder of DML operations can still succeed.


Instead of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered.


So how do you choose between the two options available?


If you need the errors that occur during DML to be thrown as an Apex exception that immediately interrupts control flow --> then go for DML statements


If you need to allow partial success of DML. Using the Database class methods, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. --> then go for Database class methods


PS : Database methods also include a syntax that supports thrown exceptions, similar to DML statements.

Tuesday, 15 November 2022

New Salesforce Assert Class

 Using Assertion.Fail() to intentionally return a fatal error.

Using Assertion.isInstanceOfType() to assert object instance.


ex : 


try {

    Test.startTest();

    SomeClass.someMethod();

    System.Assert.Fail('Throw custom exception);

 } catch (Exception baseException) {

     System.Assert.isInstanceOfType(baseException, 

                                   SomeClass.SomeCustomException, 

                                   'Expected an instance of SomeCustomException');

 }

  

Using Assert.isNull() to assert the null values.


 ex :  

  Opportunity opp = OpportunityService.getRecentClosedOpportunity();

  System.Assert.isNotNull(opp, 'Expected the opportunity to not be null'); 

  System.Assert.isNull(calloutResponse, 'Expected a null response');


Using Assert.areEqual() instead of System.assertEquals() for clarity.


ex : 


Account acc = new Account();

acc.Name = 'Test Account';

insert acc;

System.Assert.areEqual('Test Account', acc.Name, 'Expected account name to be Test Account');


String sub = 'abcde'.substring(2);

System.Assert.areNotEqual('xyz', sub, 'Characters not expected after first two');


Using Assert.isTrue() instead of System.assert() for clarity.


ex:   

  

Boolean containsForce = 'Salesforce'.contains('force'); 

System.Assert.isTrue(containsForce, 'Expected true result.');

System.Assert.isFalse(containsForce,'Expected false result.');

System.Assert.isTrue(insertResults.isEmpty());


Note :


Write System.Assert.areEqual instead of Assert.areEqual and you can safely use the new classes.

Sunday, 13 November 2022

Upgrade Behavior Options of Unlocked Packages :

 Options when installing the unlocked packages.

1.Mixed Mode (Default behavior) :

Specifies that some removed components are deleted, and other components are marked deprecated.

2.Deprecate Only :

DeprecateOnly specifies that all removed components must be marked deprecated. 

The removed metadata exists in the target org after package upgrade, but is shown in the UI as deprecated from the package. 

This option is useful when migrating metadata from one package to another.


3.Delete :


Delete specifies to delete all removed components, except for custom objects

and custom fields, that don't have dependencies.

ex :

sfdx force:package:beta:install --package 04t... -t DeprecateOnly