Use Intention-Revealing method names

Does this code smell ?

String request = requestWithHeader.substring(HeaderData.LENGTH);

This looks okay in principle. Now let me ask you, what happens when this line of code is executed ?

Because most probably you are well aware of the API of the String class, you’ll be able to answer that when this lines is executed, the substring of requestWithHeader that begins with the character at the index HeaderData.LENGTH is assigned to variable request.

But, that’s not the answer I’m looking for, I actually want more insight into the structure of the code this line belongs to.

Let me show this other version of the same code.

String request = stripHeader(requestWithHeader);

String stripHeader(String requestWithHeader) {
  return requestWithHeader.substring(HeaderData.LENGTH);
}

I believe that now you should be able to provide a straightforward and informative answer to the question, what happens when this line of code is executed ?

I am most certainly not talking about something new, most developers actually do favor the second approach, but I believe it’s way too easy to forget how much clarity a small change like this could bring to your code, specially when read by others.

This approach is documented in Ken Beck’s book Implementation Patterns.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply