Apex Class

Apex Shorthands

Apex shorthands are techniques that can significantly abbreviate your code without sacrificing readability or functionality. These shorthands not only save you time but also make your code more elegant and maintainable.

Here are some shorthands for Apex with examples that you could use on your code:

DML and SOQL Limits in Salesforce

Ternary Operator

You can use a ternary operator instead of the basic and boring if. A variable declaration is required to use an Apex ternary operator

Integer result = (condition) ? 1 : 0;

// Example
Boolean isMinor = age >= 18 ? false : true;

Variable Declaration

You can declare more than one variable of the same type in a single line of code, here is how you can do it:

Integer a = 1, b = 2, c = 3;

Map Literal

This is a shorthand to initialize a Map with key and values using a literal notation

Map<String, Integer> myMap = new Map<String, Integer>{'one' => 1, 'two' => 2};

List Initialization

Here you can initialize a List with their values, saving some lines of code later to fill it.

List<Integer> myList = new List<Integer>{1, 2, 3};

Map Initialization with SObjects

You can initialize a Map of sObjects directly with the sObject records in only one line of code! The key will be the Id (you cannot use other field) and the value will be the sObject record.

Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account]);

Remember that if later on the code you need to use only the Ids you have the map.keySet() method.

List Shorthand

If you do not want to use the keyword List to declare a list, you can avoid it using [].

Account[] accountList = new Account[]{};
String[] strList = new String[]{};

Remember that with this method you need to use {} instead of () at the end of the initialization.

Integer Addition and Subtraction

Once you have an Integer defined on your code, there is no need to use "num + 1" or "num - 1", instead you can use this method:

Integer increase = 0;
Integer decrease = 10;

System.debug(increase); // 1
System.debug(decrease); // 9

This is mostly common used on iterations, but you can use wherever you want on your code.

Add Value to Variable

This method could be useful when you need to change a variable adding another value, could it be a String, Integer, Double etc. It will help you to not write the variable twice to include a new value, this is the example:

Double totalValue = 100;
totalValue += 50;

system.debug(totalValue); // 150

Same as above, this method is common used on iterations but feel free to use it wherever you want.

String Conversion

When you want to convert a variable into a String you normally use String.valueOf which is correct, but there is other way to do it. You can use + '' and it will convert the variable into a String

Boolean primaryMember = false;
String primaryMemberStr = primaryMember + '';