Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
    
Show us your code for whatever the fragment object is. In what way is the fragment.setT1RadioGroup different from fragment.setT2RadioGroup? –  Simon André Forsberg Jan 17 at 13:03
add comment

1 Answer

up vote 5 down vote accepted

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)

share|improve this answer
    
Very good answer. Thanks for your help. –  Sharifur Rahman Jan 17 at 13:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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