Last week we dove right in with a formula from SteveMo. This week, I want to take a small step back and rather than just transform a formula into Apex, I’d like to talk on a more general level. Often times our formulas are checking for equality between two fields, or one field and some expected value. There are numerous ways to do this in formulas, but I wanted to show you some ways that you can check for equality in Apex as well.

Lets start off with with something simple, like checking if the value of a picklist is equal to some known value. In a formula one would have:

ISPICKVAL(MyField__c, 'Some Value')

In apex however, we don’t need the “ISPICKVAL” and we use the double equals to check for equality as such:

MyObject.MyField__c == 'Some Value'

The above is usually put within an if statement or its result assigned to a variable like this:

if(MyObject.MyField__c == 'Some Value') { //do geek things here }

–or–

myBooleanVariable = (MyObject.MyField__c == 'Some Value')

Now lets talk about checking for inequality. Normally this is wrapped in a NOT function within a formula like so:

NOT(ISPICKVAL(MyField__c, 'Some Value'))

In apex we check for not equals usually using the not equal operator (!=):

MyObject.MyField__c != 'Some Value'

Again we put this in if statements or assign to variables as shown above. There are also the >,<, and <> operators but these function identically in apex as they do in formulas:

Some_Value > 0 Some_Value < 0 Some_Value <> 'some other value'

For some the ‘<>‘ operator may be new, its another way of checking for inequality and I prefer to use that method in formulas but use the != notation in apex. I’m not sure why I prefer it that way other than that’s just what I’ve been using in other languages since I started programming and that’s a 15 year habit that I don’t see me breaking anytime soon.

I apologize if this week’s lesson feels a bit light, but you can help with that. Send me your formulas! :)

Until next time

:wq!