A readable way to concatenate many strings in java

I have code written very mysteriously. This will surely be a nightmare for those who do not understand me.

These are the fuzziness of string concatenation, the ternary operator, and the concatenation using the + operator.

So my question is how to 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 understand this question is subjective. And I believe that it belongs to the codexview stackexchange site. Can it be moved there?

+4
source share
3 answers

Since the first line of the line turns out 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()); 
+4
source

There are many options, but if your goal (as it usually should be) is your goal, be a little more detailed.

  • Use if-then, not ?:
  • Use +, not concat ()
  • Use a temporary variable or two (which the compiler will optimize)

So:

 String narration = "Receipt No."; if (tb.getTally_mode().equals("Ca")) { narration += tb.getTally_receipt_no() + ", " + tb.getTally_mode(); } else { narration += tb.getTally_receipt_no() + ", " + tb.getTally_mode() + ", " + tb.getTally_instrument_no() + ", " + tb.getTally_instrument_date() + ", " + tb.getTally_instrument_bank(); } tb.setTally_narration(narration); 
+4
source
  String rNum = tb.getTallyReceiptNum(); String mode = tb.getTallyMode(); String iNum = tb.getTallyInstrumentNum(); String iDate = tb.getTallyInstrumentDate(); String iBank = tb.getTallyInstrumentBank(); String narration = String.format("Receipt No. %s, %s", rNum, mode); if(! "Ca".equals(mode)){ narration = String.format("%s, %s, %s, %s", narration, iNum, iDate, iBank); } 
  • Method names in Java format.
  • String.format() allows you to format changes in the future.
  • calling equals() on a non-empty String ("Ca") reduces the likelihood of a possible NPE.
+4
source

Source: https://habr.com/ru/post/1500350/


All Articles