I have a wrapper class.
public class wrapperClass{
String s;
Date d;
Integer i;
Id id;
}
There are different operations for which certain fields are required on these wrapper object. Example 1. for functionality 1 => only Date d and String s
is required , 2. for functionality 2=> only d,i and Id
are required fields to be available. As the class grows and new functionality comes in I would need to check for the required fields based on the new functionality.
So I decided to create a reusable method to validate required fields:
public List<WrapperClass> validate( List<WrapperClass> wrapperClass) {
List<WrapperClass> validRecords = new List<WrapperClass>();
for (WrapperClass obj : WrapperClass) {
if (checkRequiredFields(obj)) {
// its valid record
validRecords.add(obj);
} else {
// not valid
}
}
return validRecords;
}
private Boolean checkRequiredFields(
WrapperClass obj
) {
if (
obj.s != null &&
obj.d != null
) {
return true;
} else {
return false;
}
}
My thought is to send the required fields to be checked as a Set to validate()
method and keep things more generic so that it can be reused everywhere. Like below. I pass reqFields Set which would consist of which fields should be checked for !=null
.
public List<WrapperClass> validate( List<WrapperClass> wrapperClass, Set<String> reqFields) {
}
However I am facing a challenge on how I could use this reqFields to check against the wrapperClass Obj. I thought of using a Map where String would have reqFields and Object will have values from wrapperClass Obj. However it will fail in runtime.
String key = 's';
Map<key,obj.key>
So that I can use this Map to check and make things more generic.