h1

What is your coding style?

February 6, 2010

I wanted to traverse a list of strings until a certain string occurred, then do something with that index. My code was:

int i;
for (i=0; i<list.size() && !("string".equals(list.get(i))); i++);
// do something with i

During the build, where we use several tools and metrics, Checkstyle complained that an empty statement in the for-loop was badness. Why?

This of course led to an argument about whether this is easy code to read. Checkstyle was happier when the above code was refactored to:

int i;
for (i=0; i<list.size(); i++)
  if ("string".equals(list.get(i)))
    break;
// do something with i

And another way to write the same code is:

int i;
while (i < list.size() && !(“string”.equals(list.get(i))))
i++;
// do something with i

The 1st and 3rd ways are crystal-clear to me and intuitively, the way I write (and think about) code.

Another example I have (and which is perhaps a deeper question about how you approach mathematical problems) is, “How do you compute a to the power of b?”. I would, instinctively, write a recursive method. Others I know would do it iteratively. What is your coding style?

Advertisements

2 comments

  1. if (list.indexOf(“string”) > -1)
    doSomethingWith(list.get(list.indexOf(“string”)));


  2. Wow, that’s cool – didn’t even realise that a list has an indexOf method!



Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: