Explaining a small example why we should use validations over apex. The key benefit is we don't have to write test class for it. Also if salesforce provide powerful tools like validations and workflows then why write APEX.
I was jumping here and there in my code to find places where I can re-factor it to reduce code lines, what I got is this.
public boolean validatePhone(account acc)
{
if (acc.Phone != null)
{
String phoneNumber = acc.Phone ;
Pattern phonePattern = Pattern.compile('\\D*?(\\d\\D*?){10}');
Pattern numericPattern = Pattern.compile('[0-9]{10}');
Matcher phoneMatcher = phonePattern.matcher(phoneNumber);
if(phoneNumber.length() == 10)
{
Matcher numericMatcher = numericPattern.matcher(phoneNumber);
if(numericMatcher.matches())
{
return true;
}
else
{
return false;
}
}
else
{
return false ;
}
}
}
A apex code which validates a phone number, I am posting with some alterations as removing some unwanted code so please don't blame me if this code doesn't work after copy and paste.
Why I have written this code? Because if any user entering value in phone field then I want them to enter value in particular format i.e. (XXX)XXX-XXXX and it should be of 10 digit.
Then I just gave a thought over using validations and came up with a solution, writing a validation on account :
Now I don't need to write any code and any test class for it. I know there are some flaws in it but what my point is how we can reduce the apex code. Now don't just give a devil smile and start looking for the flaws.
No comments:
Post a Comment