Good code is Short, Simple, and Robust
For the robust, an error is an information.
If we can sum up the definition of good code, in a nutshell, it will be as below.
“Good code is short, simple, and robust — the challenge is figuring out how to get there.”
The 1st two prerequisites can be satisfied by writing clean and beautiful code. We can gradually acquire mastery in the same with continuous practice and perseverance.
The 3rd perquisite “Robust” is a bit trickier. Besides mastery over the code, we also need to exercise a lot of prudence here.
Prudence in using exceptions; specific means by which the code can pass along errors or exceptional events to the code which called it. In simpler terms, we are telling that “Hey, I don’t know how to handle this!! Hope someone else knows it better.”
And, exception handling is a judgment call most of the times between “robustness” and “correctness”. “Correctness” implies, never returning an inaccurate result while “robustness” means always trying to do something that will allow the software to keep operating even if it leads to inaccurate results.
The trick is to strike the right balance while using exceptions. Used judiciously they can reduce code complexity. Used imprudently, they can wreak havoc on your code and make it impossible to follow and maintain.
And here are some of the ways that can be used to use exceptions in the right way.
Think Locally First. Don’t use exceptions to pass the buck
While implementing a programming unit, we make assumptions about the caller. Sometimes, these assumptions become invalid during the course of time. It is also possible that we have made the incorrect assumptions about the caller in the first place.
We therefore not only need to think about what to do if those assumptions are true but more importantly what to do if the assumptions are broken. This not only helps us make robust programs but also programs that are more re-usable.
The rule of thumb is that we need to throw exceptions only for those conditions which are truly exceptional.
Exceptions are a tradeoff between handling unexpected conditions versus increasing complexity. Whatever can be handled locally should be handled locally only.
Include all information that led to it
The unwritten rule to achieve this is Throw Early, Catch Later.
When an erroneous state is encountered in a program unit, we must throw an exception right at that point because it is here where you will have the most precise information about the error along with the context in which the exception has occurred.
Whether it is a class, interface or routine, it is important that exceptions need to be thrown out from the right level of abstraction. Once raised, the calling program catches the exception and decides to display a suitable error message should the exception be raised.
This is not only beneficial for the support personnel but also helps us to get the root cause in a much faster time.
Use Exceptions with the right messaging
The very purpose of an exception is to notify other parts of a program in such a way that they cannot be ignored.
And for this, it is very important to associate it with the right type of messaging-whether as an error, warning or information.
An error message alerts users of a problem that has already occurred. By contrast, a warning message alerts users of a condition that might cause a problem in the future.
A typical modal error message should do the following.
· Inform users that a problem occurred, explain why it happened, and provide a solution so users can fix the problem.
· Users should either perform an action or change their behavior as the result of an error message.
A typical warning message is a modal dialog box, in-place message, notification, or balloon that alerts the user of a condition that might cause a problem in the future.
The fundamental characteristic of warnings is that they involve the risk of losing one or more of the following:
· A valuable asset, such as important financial or other data.
· System access or integrity.
· Privacy or control over confidential information.
· User’s time (a significant amount, such as 30 seconds or more).
Well-written, helpful messages are crucial to a quality user experience. Poorly written messages result in low product satisfaction and are a leading cause of avoidable technical support costs.
Unnecessary error messages break users’ flow and result in making the code fat and unwieldy.
Standardize your exceptions.
Exception handling needs to be made manageable across applications and for that, it is very important to standardize them into a common framework.
A standardized exception handling framework not only makes applications easier to maintain and debug but also results in cleaner and simpler code. Some of the ways in which it can be done can be.
· Create project specific exception classes as required.
· Define circumstances for local exceptions
· Define circumstances for global exceptions.
· Determine whether a central exception reporting needs to be used.
· Aggregate your logs in a single place, preferably a database.
· Make that database accessible from a web browser.
Once you have a standard framework in place, you’ll be able to:
· Troubleshoot issues in a matter of seconds.
· Enable your support staff to determine root causes without involving you.
· Prevent testers from creating multiple tickets for the same bug.
· Save money for your business.
· Keep your weekend and reputation intact.
And Finally be very defensive about using exceptions
Sometimes the best response to a serious runtime error is to just release all acquired resources and just abort the program. Let the user rerun the program with proper inputs. It is really not worth the effort put in.
Too much of exceptions creates problems of its own. If you start checking data passed as parameters in every conceivable way and in every conceivable place, your program will be fat and slow. What is worse is that the additional code added for creating exceptions adds complexity to the program.
As Al Viro has rightly said.
The trick is to fix the problem you have, rather than the problem you want.
About the author-:
Ravi Rajan is a global IT program manager based out of Mumbai, India. He is also an avid blogger, Haiku poetry writer, archaeology enthusiast and history maniac. Connect with Ravi on LinkedIn, Medium and Twitter.