1

我有以下代码:

import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;

...
builder = newBuilder(id, Email.CONTENT_ITEM_TYPE, bUpdate);
if (bPref) {
    builder.withValue(Email.TYPE, Email.TYPE_CUSTOM);
    builder.withValue(Email.LABEL, "PREF");
} else if (iType != -1) {
    builder.withValue(Email.TYPE, iType);
}
builder.withValue(Email.DATA, value);
ops.add(builder.build());

builder = newBuilder(id, Phone.CONTENT_ITEM_TYPE, bUpdate);
if (bPref) {
    builder.withValue(Phone.TYPE, Phone.TYPE_CUSTOM);
    builder.withValue(Phone.LABEL, "PREF");
} else if (iType != -1) {
    builder.withValue(Phone.TYPE, iType);
}
builder.withValue(Phone.DATA, value);
ops.add(builder.build());

builder = ...
...

这些块非常相似,我想为它们编写一个函数。

例如:

void build(xxx name) {
  ...
  if (bPref) {
    builder.withValue(name.TYPE, name.TYPE_CUSTOM);
    builder.withValue(name.LABEL, "PREF");
  } else if (iType != -1) {
    builder.withValue(name.TYPE, iType);
  }
  builder.withValue(name.DATA, value);
  ops.add(builder.build());
}

...
build(Email);
build(Phone);
build(...);

或者有没有办法将这些重构为函数?

4

1 回答 1

0

这是我可以弄清楚如何使其成为功能的唯一方法:

void build(String itemType, String fieldType, int typeCustom, String label, String data) {
}

...
build(Email.CONTENT_ITEM_TYPE, Email.TYPE, Email.TYPE_CUSTOM, Email.LABEL, Email.DATA);
build(Phone.CONTENT_ITEM_TYPE, Phone.TYPE, Phone.TYPE_CUSTOM, Phone.LABEL, Phone.DATA);
build(Website.CONTENT_ITEM_TYPE, Website.TYPE, Website.TYPE_CUSTOM, Website.LABEL, Website.DATA);

它不像我预期的那样简洁,但比原来的重复块要好。

于 2013-10-09T03:14:06.317 回答