Exceptions are a great way of separating happy path versus trouble path. But we tend to over-complicate our solutions.
TL;DR: Don't nest Exceptions. Nobody cares of what you do in the inner blocks.
- Readability
- Refactor
try {
transaction.commit();
} catch (e) {
logerror(e);
if (e instanceOf DBError) {
try {
transaction.rollback();
} catch (e) {
doMoreLoggingRollbackFailed(e);
}
}
}
// Nested Try catches
// Exception cases are more important than the happy path
// You use exceptions as control flow
try {
transaction.commit();
} catch (transactionError) {
this.withTransactionErrorDo(
transationError, transaction);
}
// transaction error policy is not defined in this function
// so you don't have repeated code and code is more readable
// It is up to the transaction and the error to decide what to do
We can detect this smell using parsing trees.
- Exceptions
Don't abuse exceptions, don't create Exception classes no one will ever catch, and don't be prepared for every case (unless you have a good real scenario with a covering test).
The happy path should always be more important than exception cases.
Code Smell 73 - Exceptions for Expected Cases
Code Smell 26 - Exceptions Polluting
Photo by David Clode on Unsplash
Thanks to @Rodrigo for his inspiration
%[https://twitter.com/_rodrigomd/status/1403359513965731843]
Writing software as if we are the only person that ever has to comprehend it is one of the biggest mistakes and false assumptions that can be made.
Karolina Szczur
Software Engineering Great Quotes
This article is part of the CodeSmell Series.