多个值测试,如何替换许多其他if语句?

时间:2016-04-25 10:19:13

标签: java android performance if-statement android-studio

在我的Android应用程序中,我正在测试一些字符串(我从另一个活动回来),看看它们是否为空。如果没有,我从这些值构建我的URL,例如:(EDITED)

    //country only
    if (!fetchData_country.isEmpty() && fetchData_city.isEmpty() && fetchData_pmin.isEmpty() && fetchData_pmax.isEmpty()){
        query_url = URL_PRODUCT + "?" + URL_SEARCH_COUNTRY + id_country + URL_LANGUAGE;
        Log.i("INFO", "Url country only : " + query_url);
    }
    //country & price min
    else if(!fetchData_country.isEmpty() && fetchData_city.isEmpty() && !fetchData_pmin.isEmpty() && fetchData_pmax.isEmpty()) {
        query_url = URL_PRODUCT + "?" + URL_SEARCH_COUNTRY + id_country + "&" + URL_SEARCH_PRICE_MIN + id_pmin + URL_LANGUAGE;
        Log.i("INFO", "Url country & price_min : " + query_url);
    }

    //city & price_min
    else if(fetchData_country.isEmpty() && !fetchData_city.isEmpty() && !fetchData_pmin.isEmpty() && fetchData_pmax.isEmpty()) {
        query_url = URL_PRODUCT + "?" + URL_SEARCH_CITY + id_city + "&" + URL_SEARCH_PRICE_MIN + id_pmin + URL_LANGUAGE;
        Log.i("INFO", "Url city & price_min : " + query_url);
    }

    // country & city & pmin
    else if(!fetchData_country.isEmpty() && !fetchData_city.isEmpty() && !fetchData_pmin.isEmpty() && fetchData_pmax.isEmpty()) {
        query_url = URL_PRODUCT + "?" + URL_SEARCH_COUNTRY + id_country +  "&" + URL_SEARCH_CITY + id_city +  "&" + URL_SEARCH_PRICE_MIN + id_pmin + URL_LANGUAGE;
        Log.i("INFO", "Url country & city & pmin : " + query_url);
    }//many values to test still... 

我想知道如何改进这些测试部件,感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

写一些与此相似的内容

String query_url = URL_PRODUCT + "?" + (!fetchData_country.isEmpty() ? "URL_SEARCH_COUNTRY + id_country " : "")
            +(!fetchData_country.isEmpty() ? "&":"" )+ (!fetchData_pmin.isEmpty() ? " + URL_SEARCH_PRICE_MIN + id_pmin  " : "")
            +(!fetchData_pmin.isEmpty() ? "&":"" )+ (!fetchData_city.isEmpty() ? " + URL_SEARCH_CITY + id_city  " : "");