简体   繁体   中英

Can I use the Conditional Operators in a non-assignment situation in JAVA?

In case of assignment the situation is simple,

result = testCondition ? value1 : value2;

But what if I want to use it instead of an if statement? for instance in a logging situation:

logger.shouldDebbug ? logger.log("logging") : (what to do if not?);

In the case I don't what to do anything in the case of false, can I still use this Operator?

Yes you can if you wrap them in a returning function, but no you shouldn't.

In your example of the logger, let your logger output to void, discard the input when debugging isn't enabled.

You do not want to riddle your code with all these logging checks. Perform a check as least and as central as possible.

Either have a check in the logger.log function if debugging is enabled, or replace the logger with a dummy mock that does nothing except accept input and immediately discard it.

If you use standard logging frameworks like log4j you can set debugging levels, where you show only info or more serious, only warnings or more serious, only errors or more serious.

The same goes for other "quick" checks. If you find yourself using a certain pattern a lot, write a utility class for it with a static method if need be, so you have one place, where you have to change stuff, instead of 200 code points that you have to update when going to production.

You could use it if you insist, by defining a meaningless variable and take advantage of the functions' side-effects , but that's not a very good coding habit. It's purely a work-around .

For example:

public static boolean test() {
    return 1>0;
}

public static int success() {
    System.out.println("true");
    return 0; // has no meaning whatsoever
}

public static int fail() {
    System.out.println("false");
    return 0; // has no meaning whatsoever
}

public static void main(String[] args) {
    int meaningless = test() ? success() : fail();
}

Everything has been explained in comments, so I will put here only some idea:

public class Ternary {
    private final boolean condition;
    private Ternary(boolean condition) { this.condition = condition; }
    public static Ternary of(boolean condition) { return new Ternary(condition); } 
    public Ternary onTrue(Runnable r) { if (condition) { r.run(); } return this; }
    public Ternary onFalse(Runnable r) { if (!condition) { r.run(); } return this; }
}

Example of usage:

Ternary.of(o != null).onTrue(() -> doSomething()).onFalse(() -> doSomethingElse());

But simplier would be to write:

if (o != null) { doSomething(); } else { doSomethingElse(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM