Difference between dynamic boolean expression variable and boolean function

231 views Asked by At

I came across this doubt: what is the difference between these two ways of getting a boolean value? The end result is the same, but what are the advantages and disadvantages of using one or the other? What's the most used approach? What is the best practice of this coding style?
Dynamic boolean expression variable

...
public class MainActivity extends AppCompatActivity {
    private boolean isVersionM = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    ....
    private void onCreate(Bundle savedInstanceState) {
        ....
        if (isVersionM) {
            ...
        }
        else {
            ...
        }
        ...
    }
    ....
}

Boolean function

...
public class MainActivity extends AppCompatActivity {
    ....
    private void onCreate(Bundle savedInstanceState) {
        ....
        if (isVersionM()) {
            ...
        }
        else {
            ...
        }
        ...
    }
    ...
    private boolean isVersionM() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
    ...
}
1

There are 1 answers

0
Khemraj Sharma On BEST ANSWER

These are two ways to do one thing. But what if you have some run time value to calculate, then you will need second way.

What is the best practice of this coding style

Second, because you will not need to change your style for run time calculation methods like below method.

private boolean isUserLoggedIn() {
    return PreferenceManager.getString("token") != null;
}