Apex is very powerful to use if you cannot reach a solution declaratively. Ensuring the code is built correctly is only 1 part of a whole process to ensure the solution is delivered as smoothly as possible. One of the easiest things to get wrong can be assigning variables the incorrect data type which can lead to a whole host of issues further down the line, from ridiculously long and difficult to pick apart error messages to poorly kept or incorrect data.
So to avoid this, we first need to understand the most common data types. Some of these are universally used in whatever programming language you choose, and some are native to Salesforce.
|Boolean isSaturday = false;
|Can either be true or false
|Date date = date.today();
|Indicates a date
|Time time = DateTime.now().time();
|Indicates a time
|DateTime dt = DateTime.now()
|Indicates a date & time
|Decimal decimal = 99.99;
|Whole number with a decimal up to tenths
|Double double =1.23456;
|Offers a wider range than just the decimal
|Integer int = 1;
|A whole number
|Long long = 123456789L;
|A 64-bit number that does not include a decimal point.
|ID acc1 = ‘001000000317TPL’;
|An 18 character record identifier
|Account acc = new Account();
|Represents a row of data
|String welcome = ‘Welcome!’;
|A sequence of characters
So now we understand some of the data types used in Salesforce development and what values we can assign to them, let’s move on to how we can use these to declare variables.
More specifically, local variables, are declared pretty much how they’re declared in the table above, you define what data type you want, then you give it a name, and finally a default value.
Integer thisIsAnInt = 12; String message = "SFDXHours.com is the best"; boolean areWeTheBest = true;
You are also able to create multiple variables within the same line, and also assign them no default value.
Double x, y, z;
And finally, we can also declare variables where the value cannot change. We can do this using the word final before the data type.
final int tax = 20;