user1316498
user1316498

Reputation:

Is there a shorter way to write this?

I'm wondering if it's possible to write this in one-liner form.

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();

I thought maybe something like this:

(config.getBoolean("storecommands.use-time")) ? first : last;

but then I remembered that that only works for setting variables.

Does anyone know if something like the first block of code can be written in one line w/o brackets, etc.

Upvotes: 0

Views: 115

Answers (5)

arshajii
arshajii

Reputation: 129497

You can use the conditional operator here, but it'll probably come at the cost of readability, so I would reconsider. In any case, you can do:

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);

Writing this all on one line is simply a bad idea, so I've split it up to span multiple lines.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

You could use a ternary like so (but it's ugly, and you still need a close() or a 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.

Upvotes: 0

Orel Eraki
Orel Eraki

Reputation: 12196

Yes, But readability is more important than length (In reasonable amount).

Additionally, I've used a ternary condition that will inject the formatted date OR string empty, thus allowing us to freely add e.getMessage Once.

out.println((config.getBoolean("storecommands.use-time") ? "[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: " : "") + e.getMessage());
out.close();

Upvotes: 4

nhgrif
nhgrif

Reputation: 62052

private String foo(boolean b) {
    if(b) {
        return new String("[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) + "]: ");
    } else {
        return "";
}

Then simply do this:

out.println(foo(config.getBoolean("storecommands.use-time") + e.getMessage());
out.close();

Upvotes: 1

christopher
christopher

Reputation: 27336

Not one line, but two lines:

out.println(config.getBoolean("storecommands.use-time")) ? 
"[" + (new SimpleDateFormat("MM/dd/yy HH:mm:ss")).format(new Date()) 
+ "]: " + e.getMessage()) : e.getMessage());

out.close();

But that is possibly the worst thing I've ever seen and you should never ever do this in production code. If you do I will know, and we will find you.

Upvotes: 0

Related Questions