Avoid print calls in production code when using conditional statement

Viewed 88

If I use classic condition it works.

if (kDebugMode) {
    print(e.toString());
}

If I use conditional statement there is a warning:

Avoid print calls in production code.

kDebugMode ? print(e.toString()) : {};

What's wrong with oneliner solution?

2 Answers

What's wrong with oneliner solution?

Lots of things. You are obfuscating your code. You changed a super easy to understand if to a statement that is harder to parse for humans. You also added additional code that does nothing, just because the statement you picked for your logic requires it.

In short, yes, it works, but you picked the wrong language feature for what you want to do. You want to do X if Y is Z. That is best done using an if. The ? operator is exactly that: an operator with a result. But you don't actually need a result so it looks convoluted and bloaty with dead code you had to add to make the compiler happy.

You need an if. So use an if. Not a different feature that if you torture it enough will give you the same result.

If you want that to be in one line, wrap your if in a method and call that instead. Might be a good idea anyway.

  kDebugMode == true ? print(e.toString()) : {};
Related