简体   繁体   中英

large amount of if else refactor

There is a if/else statement in my code and Im thinking of refactoring it.I have already searched many Similar Questions.like this . The best answer said that the chain-of-responsibility pattern is a good choice.But below is a part of my code. If I use the CoR pattern I will create more than 70 java classes and create an ArrayList to keep instance of those classes.It will consumes more memory. I also learned about state pattern.Also need so many classes to be create.

just want to know is there a more elegant way to resolve it?

if (urlContent.contains(YLWFX)) {
  urlContent = urlContent.replace(YLWFX + ":", "");
  if (urlContent.startsWith(TRANSMIT)) {
    mProcess.onTransmit(activity, url);
  } else if (urlContent.startsWith(TAKEORDER)) {
    mProcess.onTakeOrder(activity, url);
  } else if (urlContent.startsWith(GOODS)) {
    if (urlContent.contains(GOODSMANAGER_MMZL)) {
      mProcess.onEnterpriseShopManage(activity, url);
    } else {
      mProcess.onGoods(activity, url);
    }
  } else if (urlContent.startsWith(SUPPLIER)) {
    mProcess.onSupplier(activity, url);
  } else if (urlContent.startsWith(POSTS)) {
    mProcess.onPosts(activity, url);

  } else if (urlContent.startsWith(TEAM)) {

    if (urlContent.contains(TEAM_LIST)) {
      mProcess.onTeamList(activity);
    } else if (urlContent.contains(TEAMINDEX)) {
      mProcess.onTeamIndex(activity, url);
    } else if (urlContent.contains(TEAMINFO)) {
      mProcess.onTeamInfo(activity, url);
    } else if (urlContent.contains(TEAMMEMBER_INFO)) {
      mProcess.onTeamMemberInfo(activity, url);
    } else {
      mProcess.onTeam(activity, url);
    }
  }
}

If you don't want to go down the CoR path, I'd suggest using switch statements. It'll help make your code more readable while not changing the logic. So it would look something like this: (this is just pseudocode obviously)

if(contains){
    //you will need to look at how to add this to a switch properly,
    //just giving you an idea of how I'd look at it.
    switch(urlContent.startswith) {
        case TRANSMIT:
            mProcess.onTransmit(activity, url);
        case TAKEORDER:
            mProcess.onTakeOrder(activity, url);
        case GOODS:
            if (urlContent.contains(GOODSMANAGER_MMZL)) {
                mProcess.onEnterpriseShopManage(activity, url);
            } else {
                mProcess.onGoods(activity, url);
            }
        case SUPPLIER:
            mProcess.onSupplier(activity, url);
        case POSTS:
            mProcess.onPosts(activity, url);
        case TEAM:
            if (urlContent.contains(TEAM_LIST)) {
                mProcess.onTeamList(activity);
            } else if (urlContent.contains(TEAMINDEX)) {
                mProcess.onTeamIndex(activity, url);
            } else if (urlContent.contains(TEAMINFO)) {
                mProcess.onTeamInfo(activity, url);
            } else if (urlContent.contains(TEAMMEMBER_INFO)) {
                mProcess.onTeamMemberInfo(activity, url);
            } else {
                mProcess.onTeam(activity, url);
            }
    }
}

You could even do another switch on the second lot of if elses that remain, but I'll leave that as an excercise ;) Here's some reading too: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Hope this helps to get you started. Let me know how it goes!

You should try considering differents alternatives of conditions like a Switch structure

switch (/*Variable*/)
{
  case /*Argument*/:
    /*Action*/;
    break;        
  default:
    /*Action*/;             
}

or ternary operator

int result = testCondition ? value1 : value2

First, the problem about lots of if-else is not exactly how many their are but how deep they are. See here about how to measure it and why programs with high deep nested if-else chains are undesirable.

Second, if-else is the most important statement of imperative languages, like java. So, put them inside a single method or spread them in a class hierarchy like in CoR does is just the natural way of the program paradigm in use.

Well, someone can say: "but maybe is something wrong with this kind of code, there are lots of if-else". In cases like that I guess that the problem itself is not the large use of if-else but, instead, maybe the method has lots of crosscut responsibilities. There are more general list of Design Patterns called "Grasp Design Pattern" and one of them says:

"High cohesion is an evaluative pattern that attempts to keep objects appropriately focused, manageable and understandable."

You can find more about Grasp Design Pattern in the seminal book of Craig Larman .

So, if the code inside a method has a lot of different things to do (format, rewrite, routing, validation and so on) there isn't other way them code it like a fat sequences of nested or not if-else statements. In that case, the solution is break the method in a finite set of other methods, inside the same class or, as proposed in CoR pattern, along several other classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM