我有一些以非常神秘的方式编写的代码。对于除我以外的任何人来说,这肯定会成为维护的噩梦。
它是字符串连接,三元运算符和使用+
运算符连接的混合。
所以我的问题是如何使这个陈述可读?
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())
);
编辑:我意识到这个问题是主观的。我觉得它属于codereview stackexchange网站。可以搬到那儿吗?
答案 0 :(得分:4)
这里有很多选择,但如果可维护性是你的目标(通常应该如此),那就更加冗长了。
所以:
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);
答案 1 :(得分:4)
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);
}
String.format()
允许将来格式化更改。equals()
,减少可能的NPE的可能性。答案 2 :(得分:4)
由于字符串的第一行看起来是相同的,我会把它写成:
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());