Refactoring if/else logic

前端 未结 14 644
醉话见心
醉话见心 2020-11-30 01:38

I have a java class with a thousand line method of if/else logic like this:

if (userType == \"admin\") {
     if (age > 12) {
          if (location == \"         


        
14条回答
  •  心在旅途
    2020-11-30 02:15

    First - use enums for userType and location - then you can use switch statements (improves readability)

    Second - use more methods.

    Example:

    switch (userType) {
      case Admin: handleAdmin(); break;
      case Student: handleStudent(); break;
    }
    

    and later

    private void handleAdmin() {
      switch (location) {
        case USA: handleAdminInUSA(); break;
        case Mexico: handleAdminInMexico(); break;
      }
    }
    

    Further, identify duplicate code and put it in extra methods.

    EDIT

    If someone forces you to code Java without enums (like you're forced to use Java 1.4.2), use 'final static's instead of enums or do something like:

      if (isAdmin(userType)) {
        handleAdmin(location, age);
      } else if (isStudent(userType)) {
        handleStudent(location, age));
      }
    
    //...
    
    private void handleAdmin(String location, int age) {
      if (isUSA(location)) {
        handleAdminInUSA(age);
      } else if (isUSA(location)) {
        handleAdminInMexico(age);
      }
    }
    
    //...
    
    private void handleAdminInUSA(int age) {
      if (isOldEnough(age)) {
        handleAdminInUSAOldEnough();
      } else if (isChild(age)) {
        handleChildishAdminInUSA(); // ;-)
      } //...
    }
    

提交回复
热议问题