Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readable way to concat many strings in java [closed]

Tags:

java

string

I have some code written in a very cryptic fashion. It is sure going to be a maintenance nightmare for anyone other than me to understand.

Its a mishmash of string concatenation, ternary operator and concatenating using + operator.

So my question is how would I make this statement readable?

tb.setTally_narration(
     tb.getTally_mode().equals("Ca") ? 
        "Receipt No. "
             .concat(tb.getTally_receipt_no())
             .concat(", "+tb.getTally_mode()) : 
        "Receipt No. "
             .concat(tb.getTally_receipt_no()+", "+tb.getTally_mode())
             .concat(", "+tb.getTally_instrument_no()+", "+tb.getTally_instrument_date()+", "+tb.getTally_instrument_bank())
);

Edit: I realize this question is subjective. And I feel it belongs to codereview stackexchange site. Could it be moved there?

like image 350
yoda Avatar asked Dec 16 '22 06:12

yoda


1 Answers

Since the first line of the string appears to be the same, I would write it simply as:

StringBuilder narration = new StringBuilder("Receipt No. ");

narration.append(tb.getTally_receipt_no())
         .append(", ").append(tb.getTally_mode());
if (!"Ca".equals(tb.getTally_mode()))
{
    narration.append(", ").append(tb.getTally_instrument_no())
             .append(", ").append(tb.getTally_instrument_date())
             .append(", ").append(tb.getTally_instrument_bank());
}

tb.setTally_narration(narration.toString());
like image 160
Trevor Freeman Avatar answered Dec 30 '22 12:12

Trevor Freeman