2

I have 50 different classes. I made a generic class(All) with all these 50 classes.

public class All {

    private First first;
    private Second second;
    private Third third;
...


//GETTERS AND SETTERS
}

I have a generic method and inside this I have this piece of code:

 All all=new All();

       String result;
       if(all.getFirst()!=null){
           result=methodA(all.getFirst());
       }
       else if(all.getSecond()!=null){
           result=methodB(all.getSecond());
       }
       else if(all.getThird()!=null){
           result=methodC(all.getThird());
       }
...

I don´t like this configuration because it´s an unreadable code for so many classes.

How can I improve this code?

Goldbones
  • 1,407
  • 3
  • 21
  • 55

3 Answers3

2

Maybe the following piece of code is helpful for you:

 All all = new All();

 String result;

 for(int i = 0; i++ < all.length(); ) {
     YourInterface element = all.get(i);
     if(element != null)
         result = method(element);
 }

where,

  • length() - amount of the classes
  • get(int index) - access method to element from index
  • YourInterface - common interface for all your classes

The next step is to use the reflection.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

You can definitely clean this up with either Reflection or creating your own version of that. You'd have something like: all.getObjects(); Then have that bounce against a 2 dimensional array to grab the method needed to invoke then call that.

If I'll pop back in later to finish this up. but until then here's some things I found:

using reflection to get objects from collection class

What is reflection and why is it useful?

Community
  • 1
  • 1
Syrrus
  • 79
  • 9
1
String result = all.getFirst() != null ? methodA(all.getFirst())
   : all.getSecond() != null ? methodB(all.getSecond())
   : all.getThird() != null ? methodC(all.getThird())
   : null;
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110