Making Your Code Decide Things
Every bit of code we’ve written so far runs straight through, top to bottom, doing the same thing every time. Which is fine for demos and useless for real software.
Conditional statements are how your code makes decisions. If this is true, do that. Otherwise do this other thing. That’s the whole idea, and you already use it constantly without thinking about it: if it’s raining, take a coat.
Integer temperature = 45;
if (temperature < 50)
{
System.debug('Take a coat');
}The bit in the brackets has to evaluate to a Boolean, true or false. If it’s true, the braces run. If not, they’re skipped entirely.
if / else if / else
Integer temperature = 75;
if (temperature < 50)
{
System.debug('Take a coat');
}
else if (temperature < 70)
{
System.debug('Take a jumper');
}
else
{
System.debug('You are fine, go outside');
}Apex works down the chain and stops at the first one that’s true. Once something matches, nothing below it even gets looked at.
That “stops at the first match” bit matters more than people expect. Order your conditions from most specific to least specific, or you’ll write something like this and wonder why the second branch never fires:
//BROKEN. Anything under 100 matches the first one,
//so 'freezing' is completely unreachable.
if (temperature < 100) { System.debug('Warm-ish'); }
else if (temperature < 20) { System.debug('Freezing'); }else is the catch-all and it’s optional. But do think about whether you want one. An if/else-if chain with no else quietly does nothing when nothing matches, which is occasionally what you want and frequently a bug you won’t notice for weeks.
Combining Conditions
The logical operators from episode 15 come into their own here:
if (opp.StageName == 'Closed Won' && opp.Amount > 10000)
{
System.debug('Big win!');
}
if (cont.Email == null || cont.Phone == null)
{
System.debug('Missing contact details');
}And remember short circuiting, because it’s the standard way to write a safe null check:
//If accounts is null, isEmpty() never runs. No exception.
if (accounts != null && !accounts.isEmpty())
{
//do the thing
}Always Use The Braces
Apex lets you skip the curly braces on a single line condition:
//Legal. Also a trap.
if (temperature < 50)
System.debug('Take a coat');Please don’t. Here’s why, and it’s one of the great classic bugs:
if (temperature < 50)
System.debug('Take a coat');
System.debug('Take gloves too'); //ALWAYS runs. Surprise.That second debug is not in the if. The indentation says it is. The compiler disagrees, and the compiler wins. Only the first line was ever attached to the condition.
Braces cost you two keystrokes and save you an afternoon. Use them every time, even for one liner.
Don’t Build The Pyramid
You can nest conditionals inside each other. After about three levels it becomes genuinely painful to read:
//Nobody enjoys this
if (opp != null)
{
if (opp.StageName == 'Closed Won')
{
if (opp.Amount != null)
{
if (opp.Amount > 10000)
{
System.debug('Big win!');
}
}
}
}Flatten it. Either combine the conditions:
if (opp != null && opp.StageName == 'Closed Won'
&& opp.Amount != null && opp.Amount > 10000)
{
System.debug('Big win!');
}Or use guard clauses, which bail out early and leave the happy path unindented:
private void checkOpportunity(Opportunity opp)
{
if (opp == null) { return; }
if (opp.StageName != 'Closed Won') { return; }
if (opp.Amount == null || opp.Amount <= 10000) { return; }
System.debug('Big win!');
}Same logic, reads top to bottom, no pyramid. Once you get used to guard clauses you’ll find it hard to go back.
What’s Next
Conditionals: if/else if/else, first match wins, always use braces, flatten your nesting.
Official docs here.
In the next episode we look at switch statements, which do a similar job in a tidier way when the conditions are simple.
See you next time!
Get Coding With The Force Merch!!
We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.
Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!
Check Out More Coding With The Force Stuff!
If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!
Youtube
Patreon
Github
Facebook
Twitter
Instagram
Salesforce Development Books I Recommend
Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps
Good Non-SF Specific Development Books:
Clean Code
Clean Architecture