Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for loop to change method name

Tags:

java

I have a list of strings and I have 10 unique methods doing different validations based on what string it is. For example this is what I have now:

if(name1 != null){
  validateName1();
}
else{
  throw Error();
}

 if(name2 != null){
  validateName2();
}
else{
  throw Error();
}
...

So instead of doing the same if-else check 10 times for all the different methods I was hoping I could store the names in a String list and have a for loop going through it in the following manner:

List<String> names = new ArrayList<String>();
for(name : names){
   if(name != null){
     validate[name]();
   }
   else{
     throw Error();
   }

Please let me know if this is possible, or if this is a rudimentary approach and there is a more elegant solution to my problem. To reiterate my problem is basically I have 10 different & unique validate methods and instead of writing if-else for each of them I want to be able to go through a for loop to call these methods with the new name.

Thanks in advance for the help!

like image 309
ItsANabhility Avatar asked Oct 31 '22 19:10

ItsANabhility


1 Answers

First, you have a different validator for every type of name. You say you have ten names:

public interface Name {
}

public class ShortName implements Name {
}

public class LongName implements Name {
}

public class MaidenName implements Name {
}

and so on. Then you have to validate a name.

public interface Name {
  public void validate();
}

which will make your other names throw compiler errors because they don't have the setName(...) method. So add it.

public class ShortName implements Name {
   private String name;

   public void validate() {
     // the first pass at validation
     if (name == null) {
        throw IllegalStateException("Name cannot be null");
     }
     // the second pass at validation
     if ("".equals(name)) {
        throw IllegalStateException("Name has a zero length");
     }
     // ok, the name is valid
   }
}

Once you have one of these for every name, you can now do this.

List<Name> names = getNames();

for (Name name : names) {
   names.validate();
}

and each type of name will run it's unique validator.

like image 56
Edwin Buck Avatar answered Nov 14 '22 18:11

Edwin Buck