Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Excel imported data

I am importing an excel sheet with 30 columns using Apache POI framework. I am reading each cell and inserting it into database.

I need to validate each of these columns for different conditions, other than using multiple if else conditions and calling different methods for each columns is there any other way to go about this?

like image 892
coder Avatar asked Oct 20 '22 20:10

coder


1 Answers

I have less experience with java. There could be multiple ways to solve your problem. However I have used Strategy Pattern to design a common validation class which can be used for different type of items without ugly if-else block. Though I had to create separate validation method for different type of fields, but I feel this is better than having lot of if else block.

interface IValidator<T> {
  boolean validate(T field);
}

class SomeFieldOne<T> implements IValidator<T> {
  public boolean validate(T field) {
    print("SomeFieldOne validation");
    return true; // return true/false based on validation
  }
}

class SomeFieldTwo<T> implements IValidator<T> {
  public boolean validate(T field) {
    print("SomeFieldTwo validate");
    return true; // return true/false based on validation
  }
}

class Context {
  private IValidator validator;

  public Context(IValidator validator) {
    this.validator = validator;
  }

  public boolean validate(String field) {
    return this.validator.validate(field);
  }
}

public class TestValidation {
  public static void main(String[] args) {
    Context context;

    context = new Context(new SomeFieldOne());
    print(context.validate("some field one"));

    context = new Context(new SomeFieldTwo());
    print(context.validate("some field two"));

    // test other fields ....
    // .........
  }
}
like image 130
Ravi Kumar Avatar answered Oct 24 '22 11:10

Ravi Kumar