It's come to my attention that you can use System.assert()
, System.assertEquals()
, etc. outside of test classes in Apex.
I've seen a lot of custom Exception classes written that do nothing but extend the Exception
class, and a lot of Apex production (i.e. non-test) code that looks more or less like this:
public class MyClass {
public class MyException extends Exception {}
public static Account getAccount(Id accountId) {
List<Account> accounts =
[SELECT Name FROM Account WHERE Id = :accountId];
if (accounts.size() != 1) {
throw new MyException(
'Did not find an account for Id ' + accountId
);
}
// ...
}
}
This is less code, and cleaner in my opinion:
public class MyClass {
public static Account getAccount(Id accountId) {
List<Account> accounts =
[SELECT Name FROM Account WHERE Id = :accountId];
System.assertEquals(
1,
accounts.size(),
'Did not find an account for Id ' + accountId
);
// ...
}
}
I know the below approach is going to throw an AssertException
, whereas you can give the exception whatever name you want in the above approach. But the name of the exception class itself seems pretty unimportant -- way less important than the message, which you can customize either way.
Are there any other drawbacks to the System.assert...
approach that I'm neglecting?