Eliminate String Concatenation

Consider the following piece of code that does string concatenation.

   1: public String validateOrderLineItem(OrderLineItem aOrderLineItem) {
   2:     if (aOrderLineItem.getPrice() == null) {
   3:         return "The order line item for product: " + aOrderLineItem.getProduct().getDescription() +
   4:                 " for order id : " + aOrderLineItem.getOrder().getId() + " must not be null!";
   5:     }
   6:     return null;
   7: }

I am not a big fan of such string concatenation. Such strings are harder to read and maintain. They are also potential performance and memory problems.

I always try to replace the code above with something that looks like this:

   1: private static final String INVALID_PRICE =
   2:         "The order line item for product: %s  for order id : %s  must not be null!";
   3:  
   4: public String validateOrderLineItem2(OrderLineItem aOrderLineItem) {
   5:     if (aOrderLineItem.getPrice() == null) {
   6:         return String.format(INVALID_PRICE, aOrderLineItem.getProduct().getDescription(),
   7:                 aOrderLineItem.getOrder().getId());
   8:     }
   9:     return null;
  10: }

At least the message is much easier to read!

There are couple of other alternatives like using MessageFormat and templating languages, but they are over kill for this example.

This example is in Java, but is equally applicable to C# and other languages.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 9/22/2009 10:42 AM Sriram Srinivasan wrote:
    Does it matter if the variable is defined locally instead of a static global variable?
    Reply to this
    1. 9/24/2009 12:54 PM Prakash Malani wrote:
      It doesn't matter if the variable was local because the way Java handles strings. But, I haven't done any testing...
      +prakash

      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name (required)

 Email (will not be published) (required)

 Website

Your comment is 0 characters limited to 3000 characters.