简体   繁体   中英

Refactoring code into function by mapping

I have following code:

...
if (...) { // Handling emails
  int emailType = -1; 
  if (types != null) {
    String type = foo(types);
    if (type.equals("work")) {
      emailType = Email.TYPE_WORK;  // android.provider.ContactsContract.CommonDataKinds.Email
    } else if (type.equals("home")) {
      veemailType = Email.TYPE_HOME;
    } else if (type.equals("mobile")) {
      emailType = Email.TYPE_MOBILE;
    } else if (type.equals("other")) {
      emailType = Email.TYPE_OTHER;
    }
    bar(emailType);
  }
} else if (...) { // Handling phones
  int telType = -1; 
  if (types != null) {
    String type = foo(types);
    if (type.equals("work")) {
      telType = Phone.TYPE_WORK;  // android.provider.ContactsContract.CommonDataKinds.Phone
    } else if (type.equals("home")) {
      telType = Phone.TYPE_HOME;
    } else if (type.equals("mobile")) {
      telType = Phone.TYPE_MOBILE;
    } else if (type.equals("other")) {
      telType = Phone.TYPE_OTHER;
    }
    bar(telType);
  }
} else if ...

Apparently I should use a function to wrap these similar handling logic, but no idea how to do it.

With C/C++ I would prefer macro in this case, but looks like there is no macro in Java?

You need to write methods for handlingPhones and Handling emails. Instead of using the if else loops you should you switch case statements. I would recomment installing various code quality plugins which will point out your code quality issues as and when you are writing your java code

One opition here is to get rid of int constants and introduce enum class with a factory method to produce values from strings:

public enum Email{
    TYPE_HOME("home"),
    TYPE_MOBILE("mobile"),
    TYPE_OTHER("other"),
    TYPE_WORK("work");

    private final String stringValue;

    Email(String stringValue) {
        this.stringValue = stringValue;
    }

    public static Email parse(String value){
        for (Email email : values()){
            if (email.stringValue.equals(value)){
                return email;
            }
        }
        throw new IllegalArgumentException("Illegal argument: " + value);
    }
}

Now you can replace if-else chain with the following:

String types = foo(types);
Email email = Email.parse(types);
bar(email);

You should create a HashMap from the string version of the email type to the Email.TYPE_*.

Then you can pass off the map to a function, eg

int clean(Map<String, Integer> typemap, String type_s) {
    return bar(typemap.get(foo(type_s)));
} 

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