Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ProGuard remove conditional code from a method that ALWAYS returns a constant?

On my Android application I've been using conditional code like this:

if(BuildConfig.DEBUG) {
    // do something...
}

And if ProGurad evalutes BuildConfig.DEBUG to false, the block of code inside the if is stripped from the final bytecode. Which is working as intended.

However, with the introduction of the new build system for Android, we now have many abilities we didn't have before. I'm taking advantage of that by creating a new buildType which I call it QA. With that I've add a BuildConfig.QA constant that will be true or false accordingly to the build type.

Now I have some pieces of code where I need to test if it's a DEBUG or a QA build, like this:

if(BuildConfig.DEBUG || BuildConfig.QA) {
    // do something...
}

But this is cumbersome to write all over the place. Instead, I've decided to create a static method on my utils class, like this:

public static boolean isDevelopmentBuild() {
    return BuildConfig.DEBUG || BuildConfig.QA;
}

The problem is that with this approach, any conditional code will not be removed as it used to be. Before, ProGuard could evaluate those constants to false and strip the code. Now, it has to call a method and check for the return value.

But since the return value of that method are constants, is it possible that ProGuard could evaluate the method call in a way that would know that the return value is always a constant value (during runtime) and remove the code from the final bytecode?

like image 864
rfgamaral Avatar asked Aug 04 '13 12:08

rfgamaral


1 Answers

Why not add a constant DEV to your BuildConfig interface, like

boolean DEBUG = ...
boolean QA = ...
boolean DEV = DEBUG | QA;

It will be a compile-time constant (given that DEBUG and QA are defined at compile-time) and so ProGuard will be able to do code elimination based on just

if (BuildConfig.DEV) { ...
like image 72
Ernest Friedman-Hill Avatar answered Sep 20 '22 15:09

Ernest Friedman-Hill