Defensive Programming

As Murphy’s Law states, “Whatever can go wrong, will go wrong”.

“If there’s more than one possible outcome of a job or task, and one of those outcomes will result in disaster or an undesirable consequence, then somebody will do it that way”.

So defensive programming is all about guarding one’s code. Never trust any external entities. So all the inputs that comes into one’s method should be scanned.

For example :
Consider this piece of java code.
public void myfun( String a, String b){
int i = a.length();
int j = b.length();

Here ‘a’ and ‘b’ can be null.
So in defensive programming it will be
if( a == null) return; if( b == null ) return;

Always be in safer side is the philosophy of defensive programming. This reduces the log debug statements as one can be sure that he has handled most of the conditions that will break his code.
Code written in this manner can be reused, since it won’t create any unnecessary bugs.

There are various techniques used in defensive programming.
Some are assertion, design by contact, return exceptions etc.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s