jeudi 21 juillet 2016

refector long if else [on hold]

What is the best way to refactor this long if else statements? make it shorter and more readable code.

I thought to use sub-classes but I don't understand how to implement that, so examples will be blessed.

Thank you!

 public void redirectFromScheme(String scheme, Context context) {

        if (!scheme.contains(SCHEMA_WALLA)) {
            return;
        }

        HashMap<String, String> params = paramsUrlSplitter(scheme);
        int itemType = Integer.parseInt(params.get(KEY_ITEM_TYPE));
        String itemId = params.get(KEY_ITEM_ID);
        String genreId = params.get(KEY_GENRE_ID);

        if (scheme.startsWith(SCHEMA_MAIN)) {
            startMainActivity("");
        }

        else if (scheme.startsWith(SCHEMA_MOVIE)) {

            if (params.containsKey(KEY_GENRE_ID))
                startGenreActivity(params.get(KEY_GENRE_ID), MOVIES_TITLE, MOVIES_ID);
            else
                startMainActivity(MOVIES_TITLE);
        }

        else if (scheme.startsWith(SCHEMA_SERIES)) {

            if (params.containsKey(KEY_GENRE_ID))
                startGenreActivity(genreId, SERIES_TITLE, SERIES_ID);

             else if (params.containsKey(KEY_SERIES_ID))
                startSeriesActivity(context, params);
             else
                startMainActivity(SERIES_TITLE);
        }

        else if (scheme.startsWith(SCHEMA_KIDS)) {

            if (params.containsKey(KEY_GENRE_ID))
                startGenreActivity(params.get(KEY_GENRE_ID), KIDS_TITLE, KIDS_ID);
            else
                startMainActivity(KIDS_TITLE);
        }

        else if (scheme.startsWith(SCHEMA_ITEM)) {
            startMediaItemActivity(itemId, itemType);
        }

        else if (scheme.startsWith(SCHEMA_SEARCH)) {

            try {
                String url = URLDecoder.decode(params.get(KEY_SEARCH_WORD), UTF8);
                startSearchActivity(context, url);

            } catch (UnsupportedEncodingException ex) {
                Log.d(TAG, ex.getMessage());
            }
        }
    }

Aucun commentaire:

Enregistrer un commentaire