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?
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 ....
// .........
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With