Friday, January 18, 2008

Small Java trick with copy - paste

Here is a small trick I use to avoid getting into problems.

Some times, I need to copy a block with a variable, for instance:
      Address addr = list.get(0);
assertEquals("city", "Uppsala", addr.getCity());
and paste it to create something similar like this:
      Address addr2 = person.getAddress()
assertEquals("city", "Uppsala", addr.getCity());
Did you see the bug?

The trick I use to avoid bugs like this, is to change the variable name in the original block:
      Address addr1 = list.get(0);
assertEquals("city", "Uppsala", addr1.getCity());
Address addr2 = person.getAddress()
assertEquals("city", "Uppsala", addr.getCity());
Then the bug becomes obvious.

I can't tell you how many times this has saved me.

5 comments:

Prashant Jalasutram said...

Hi,

Good little suggestion given.

Thanks
Prashant Jalasutram
http://prashantjalasutram.blogspot.com/

martinus said...

copy & pasting sourcecode is an extremely bad programing practice. IDEs should get rid of this "feature".

Lars said...

@martinus: That's too general, but I agree that code duplication is a huge problem.

danno said...

With super-cool IDEs like IntelliJ the unused variable is highlighted, so it will become blatantly obvious that a variable is unused. In your case, addr2 would be highlighted.

amigooo said...

Anyway, cool suggestion