Oct.14, 2009 by NickChristy

Tips and Tricks: String Manipulation

Categories: Engineering Best Practices, Thought Leadership

As engineers, one of the most common things we need to do is manipulate strings in some fashion. All of us have had to compare a value to a constant at some point in our careers as software developers. The most common code snippet that I see when doing this looks similar to:

code_1

Now take a second to ask yourself, what is wrong with this? You might write a quick unit test to pass in values like “Is THIS the same” or “This doesn’t equal” and more than likely “Is this the same”. The tests all pass and you think your job is done. Stop to think about your method again; is there something wrong? Your tests pass and you have used common practices so everything should be good. Remember the golden rule – “Always practice defensive programming”. What if I wrote a test looked like:

code_3

Ahh, a null pointer exception. Now take a second look at your code. You could go back and add a quick check for a null parameter into your code. What does that really do? Your taking care of the “defensive” programming rule, but at the same time your adding lines of code. Do you really want someone else coming into your project and reading a bunch of wasted if(object==null) statements? Not really. One quick trick would be to reverse the order of your .equals()…

code_2

Now what have we done? By simply reversing the order so that the object that is checking for the equality is a known value, we have defended against the possibility of a null value exception. No need to check to see if x is null, rather we would return false, because after all, they aren’t equal. This trick can be applied in other cases, such as casting or returning portions of strings.

I’ll leave this blog open to discussion on other ways to easily protect yourselves against the dreaded null pointer exception…

Sorry, there are no polls available at the moment.

Tags: , , ,

Leave a Reply

R2i YouTube Channel

R2i Twitter Feed

  •  

R2i Flickr Wall

 
r2i connect

Keep In Touch With r2i

Select which of the following that you would like to follow:

Please subscribe to at least one alert