## Saturday, January 30, 2016

### Salesforce Lesson 5 - More Best Practices with IFs in Formulas

Today I want to write about best practice uses of IF within formulas. Sometimes there are misuses of IFs that add extra complexity without gaining functionality.

Understanding formulas can be a science of its own.  They can become as complex as necessary but adding extra unnecessary complexity should always be avoided to make formulas error-free and more maintainable.

Lets take the case of a Validation Rule.  When embodied inside an AND( ) the following form of IF is unnecessary and NOT, in this technical engineer's humble opinion, a best practice.
Here is a simple formula example with an unnecessary IF:
AND (
X = Y,
IF(A = B, TRUE, FALSE)
)
You see the lack of necessity in the IF?
The only part necessary here is "A=B" because each line within the AND is a Boolean evaluation anyway returning TRUE when the condition is TRUE and FALSE when it is not.  Its just that simple.

The above formula should therefore be rewritten as follows:
AND (
X = Y,
A = B
)

As alluded to above an important consideration is the purpose/place of the formula?  Is it a Formula Field or is it Validation Rule or a Workflow Rule (criteria)?   The latter two always return a Boolean value whereas the former can be a Checkbox (Boolean) but can also return various other data types.  IF statements can therefore apply to returning something other than TRUE or FALSE.
For example a formula field might be written the following way:
IF (X > Y, X, Y)

Finally there can be plenty of uses of IF statements in Validation Rules to use two different Boolean evaluations.  Lets say you want an error to be evaluated two different ways - one way when field X is greater than field Y and another way when X is less than or equal to Y.  This hypothetical might be coded the following way:
IF (X > Y,
AND( Amount1 < Amount2,
FieldA = FieldB
),
A > Z
)
An alternative to this would be:
OR(
AND( X > Y,
Amount1 < Amount2,
FieldA = FieldB
),
AND( X <= Y,
A > Z
)
)

It is less complex to use the first form with the IF.  In this instance we are not assigning a static TRUE or FALSE return value which, as a general rule, is pointless.

Happy formulating!