Saturday, May 18, 2013

Eclipse, Java : Inserting Single line "if block"

If we run our program after completing coding, those will not as excepted mostly, or at-least in testing we will find places where we have missed some null check or etc. So we may have to add a if condition to check and to avoid those Exceptions. Mostly those will be a single line "if blocks".

I am talking about cases like below. Say you have following line:

myObject.myMethod();

Here we got a NullPointerException because myObject is null, I wanted added a null check before this:

if(myObject!=null)
     myObject.myMethod();

This is correct, but I mostly don't like this, for future coding and because of the readability, I prefer to add a block as follows. Sometime reader will think that, all the statements which following the above statement also inside the if condition.

if(myObject!=null){
     myObject.myMethod();
}

It was hard for me always, because I had to write if block and copy paste the statement inside. But i found a method to do in Eclipse without  doing  copy paste.

Just go infront of the statement and start typing your if condition and write up to { and press enter key, then you will get what you want.

if(myObject!=null){|myObject.myMethod(); <-- font="">Keep the curser at the | position and press enter.

Okey now you try and let me know your comments.