我想知道是否可以用单线形式写这个。
if (config.getBoolean("storecommands.use-time")) {
out.println("[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: " + e.getMessage());
else {
out.println(e.getMessage());
}
out.close();
我想也许是这样的:
(config.getBoolean("storecommands.use-time")) ? first : last;
但后来我记得那只适用于设置变量。
有没有人知道像第一个代码块这样的东西是否可以写成一行没有括号等。
答案 0 :(得分:4)
是的,但可读性比长度更重要(合理数量)。
此外,我使用了三元条件,将格式化的日期 OR 字符串注入空,从而允许我们自由添加e.getMessage
一次。
out.println((config.getBoolean("storecommands.use-time") ? "[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: " : "") + e.getMessage());
out.close();
答案 1 :(得分:1)
private String foo(boolean b) {
if(b) {
return new String("[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: ");
} else {
return "";
}
然后只需这样做:
out.println(foo(config.getBoolean("storecommands.use-time") + e.getMessage());
out.close();
答案 2 :(得分:0)
你可以使用像这样的三元组(但它很难看,你还需要close()或flush())。
// Construct this constant date format elsewhere, and save the referene!
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
// This ternary is ugly, but possible.
out.println((config.getBoolean("storecommands.use-time") ?
"[" + df.format(new Date()) + "]: " : "")
+ e.getMessage());
out.close(); // <-- might prefer flush() there.
答案 3 :(得分:0)
不是一行,而是两行:
out.println(config.getBoolean("storecommands.use-time")) ?
"[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date())
+ "]: " + e.getMessage()) : e.getMessage());
out.close();
但这可能是我见过的最糟糕的事情,你永远不应该在生产代码中这样做。如果你这样做,我会知道,我们会找到你。
答案 4 :(得分:0)
你可以在这里使用条件运算符,但它可能以可读性为代价,所以我会重新考虑。无论如何,你可以这样做:
boolean b = config.getBoolean("storecommands.use-time");
String message = e.getMessage();
out.println(b ?
"[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: " + message
:
message);
将这一切写在一行上只是一个坏主意,所以我把它拆分成多行。