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.

Does it matter if the variable is defined locally instead of a static global variable?
Reply to this
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