1
\$\begingroup\$
private void loadTabsIfGPSAndInternetAvailable()
    {
        final Utils utils = new Utils(this);
        final LocationClient locationClient = new LocationClient(this);
        if (!utils.isConnected())
        {
            utils.generateNoConnectivityAlert();
        }
        else if (!locationClient.hasGPS())
        {
            utils.generateNoGPSAlert();
        }
        else
        {
            if (androidVersion >= Build.VERSION_CODES.M)
            {
                requestAllPermissions();
            }
            else
            {
                loadCameraAndForecastTabs();
            }
        } // ends else block for if internet and GPS are enabled
    }

This is some code that loads tabs if the GPS and internet connectivity are available. I'm aware that at the moment this is very messy code, with lots of nested if statements, that is hard to read, and am not sure how to structure it better. Can people help me please?

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review! Good job on your first question. \$\endgroup\$
    – SirPython
    Commented Mar 26, 2016 at 18:21

1 Answer 1

1
\$\begingroup\$

Well, you don't need to use nested if statements here, but an if / else if ... chain seems unavoidable.

You can neaten up the code like this. Note: 12 lines of code instead of 25.

private void loadTabsIfGPSAndInternetAvailable() {
    final Utils utils = new Utils(this);
    if (!utils.isConnected()) {
        utils.generateNoConnectivityAlert();
    } else if (!(new LocationClient(this).hasGPS())) {
        utils.generateNoGPSAlert();
    } else if (androidVersion >= Build.VERSION_CODES.M) {
        requestAllPermissions();
    } else {
        loadCameraAndForecastTabs();
    }
}

However, I suspect that there is something wrong with the logic of your original code ... which would make my refactoring incorrect as well.

\$\endgroup\$
1
  • \$\begingroup\$ Wrong in what way please? \$\endgroup\$ Commented Mar 28, 2016 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.