Friday, October 28, 2016

Write your Try-Catch-Finally Statement First

In Clean Code, Uncle Bob give the following advice:

Write your Try-Catch-Finally Statement First

Why?
"... it is good practice to start with a try-catch-finally statement when you are writing code that could throw exceptions. This helps you define what the user of that code should expect, no matter what goes wrong with the code that is executed in the try."
I like this because by following this advice, you'll have to start by writing unit tests that handle exceptions for code where exceptions are expected to be thrown. And then you'll have to write the exception handling code which will force you to think about how you may want to handle the error case. In Uncle Bob's words, you'll have to "define what the user of that code should expect".

This is useful from a development efficiency standpoint because if you expect an error, then by writing the test case for when that error is thrown, you can write the code for the Try block with confidence. You know that even if something goes wrong, it will be handled and the current function will execute to its completion.

If you don't do this, then you'll write a unit test case for code that might just blow up your program and crash spectacularly. Then what? You're finally forced to heed the advice of writing the Try-Catch-Finally statement and realize that maybe you should've done that first.

No comments:

Post a Comment