3
\$\begingroup\$

I am setting different RadioGroup like this:

fragment.setT1RadioGroup((RadioGroup)fragView.findViewById(rowids[0]).findViewById(R.id.t1_radiogroup));
fragment.setT2RadioGroup((RadioGroup)fragView.findViewById(rowids[1]).findViewById(R.id.t1_radiogroup));
fragment.setT3RadioGroup((RadioGroup)fragView.findViewById(rowids[2]).findViewById(R.id.t1_radiogroup));
fragment.setT4RadioGroup((RadioGroup)fragView.findViewById(rowids[3]).findViewById(R.id.t1_radiogroup));
fragment.setT5RadioGroup((RadioGroup)fragView.findViewById(rowids[4]).findViewById(R.id.t1_radiogroup));
fragment.setT6RadioGroup((RadioGroup)fragView.findViewById(rowids[5]).findViewById(R.id.t1_radiogroup));
fragment.setT7RadioGroup((RadioGroup)fragView.findViewById(rowids[6]).findViewById(R.id.t1_radiogroup));
fragment.setT8RadioGroup((RadioGroup)fragView.findViewById(rowids[7]).findViewById(R.id.t1_radiogroup));
fragment.setT9RadioGroup((RadioGroup)fragView.findViewById(rowids[8]).findViewById(R.id.t1_radiogroup));
fragment.setT10RadioGroup((RadioGroup)fragView.findViewById(rowids[9]).findViewById(R.id.t1_radiogroup));

For refactoring purpose could I reduce the size of this code? How?

\$\endgroup\$
  • \$\begingroup\$ Show us your code for whatever the fragment object is. In what way is the fragment.setT1RadioGroup different from fragment.setT2RadioGroup? \$\endgroup\$ – Simon Forsberg Jan 17 '14 at 13:03
6
\$\begingroup\$

Assuming that setT5RadioGroup only sets a variable within the fragment:

In your fragment, use RadioGroup[] radioGroups = new RadioGroup[10];

setTRadioGroup(int number, RadioGroup grp) {
   this.radioGroups[number] = grp;
}

In your activity, or whatever it is:

for (int i = 0; i < rowids.length; i++) { // assuming rowids.length is 10
    RadioGroup grp = (RadioGroup)fragView.findViewById(rowids[i]).findViewById(R.id.t1_radiogroup);
    fragment.setTRadioGroup(i, grp);
}

Whenever you find yourself using multiple numbered methods that does very similar things, think: Array!! (or possibly List<ElementType> if you want to be able to add/remove dynamically)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.