« Back to blog

Defensive Coding

I will keep this short and simple. Today a senior of mine uttered this phrase, when i was talking ab0ut spanning out null checks all over the code. He said that it will be defensive coding and i soon realized why. The moment you have null check for everything in your code it becomes a little difficult to track down the root of the issue. While your code will be all running and may never break down, there will be issues which will look so mysterious to you that you will end up wasting an entire day just trying to debug one of them. So, while i am a proponent of exceptional handling, may i remind of the golden line: "everything in moderation". Let me give an example of how Defensive coding can be counter productive. I was debugging my code today when i started encountering object refs in my mapper functions i wrote to map the service objects to the UI objects. Now, at first glance i cursed myself for not doing the correct exceptional handling at this level. But, then i went about finding the source of the object ref. As it turned out that even after narrowing the possible issue to one function, i realized that i was using that mapper at 3 different places with in that function!! Thus, i had to debug at each place and figure it out. It was not a one glance thing. And it became so difficult simply because i had done a lot of exceptional handling in all these cases and then the odd case of corrupted was plauging me which was showing its true colors due to a missing fragment of a if-condition (4 conditions were already being tested for, and an extra 5th was now necessary). Its easy to say that the code should have handled it. But, why in God's name was such data being provided in the 1st place. Cross checks are good. But, they should not be overdone. With every stage the flows through there should lesser number of null checks required. Checking for null values or doing exceptional handling for a particular scenario or case, at the DB layer, service level and UI is plain waste of time and a level of redundancy you must avoid. Not, more than twice. It is a huge task to keep a thorough track of this, but i think that this is just another and better coding practice. Don't you?