While looking for areas to improve code coverage, I stumbled upon this trigger:
trigger checkAccountPhoneNumberBiBu on Account (before insert, before update) {
for (Account account : Trigger.new) {
if (account.Phone==null) continue;
Pattern p = Pattern.compile('[-() ]');
String sPhone = p.matcher(account.Phone).replaceAll('');
// check length without punctuation
if (sPhone.length() != 10) account.Phone.addError(' Phone number must have 3 digit area code and 7 digit number');
p = Pattern.compile('\\d');
sPhone = p.matcher(sPhone).replaceAll('');
if (sPhone.length() > 0) account.Phone.addError('Phone number must be formatted as (999)999-9999');
}
}
This trigger looks at the value entered in the "Phone" field before an Account record is inserted or updated; if the phone field is not in the (999)999-9999 format, it errors out and notifies the user to enter the phone # in the proper format.
In addition to this Apex code, the developer also had to write a testmethod to ensure coverage of the trigger. His code was only getting 67% test coverage (which is what brought the trigger to my attention in the first place).
As I started looking at what I needed to add to the testmethod to ensure 100% coverage, I realized it would be easier to just get rid of the trigger altogether, and replace it with a Validation Rule. That 10 lines of Apex code was reduced to a 1-line formula in a validation rule:
NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}"))
Here's the validation rule in the UI:
Simpler is always better. Any time you can minimize your code (or get rid of it altogether), you make your org simpler, smaller and eaiser to maintain. I'm a fan of that.
Another benefit of implementing this as a validation rule is that I'm able to control where the error message is displayed. Previously, the trigger method displayed the error message at the top of the detail record page layout. With validation rules, you can display error messages either at the top of the screen or at exact field where the error was made; I generally prefer the latter.
Want to see this and other useful validation rules? Check out the Useful Validation Formulas guide by Salesforce.com.