I have a use case of template design pattern with generics as mentioned below.
I have AbstractVerificationHandler
that provides template for verification business logic which is used by different domain verification handlers e.g UserVerifier
depending on the db type and file type POJOs. Can the below code be simplified using simpler constructs or by reducing the scope of generics?
class VerificationJob {
public void execute() {
String domainType = "user";
VerificationHandler verifier = getVerifierInstance(domainType);
boolean result = verifier.verify();
}
VerificationHandler getVerifierInstance() {
return domainType.equals("user") ? new UserVerifier() : null // or a switch case etc.
}
}
interface VerificationHandler {
boolean verify(); // omitted common inputs for verification
}
interface Identify {
String identity();
}
abstract class AbstractVerificationHandler<F extends Identity, D extends Identity>
implements VerificationHandler {
boolean verify() {
List<D> dbRecords = fetchAllDBRecords();
Map<String, F> fileRecords = identityMap(fetchAllFileRecords());
for(D record: dbRecords) {
if(!verify(record, fileRecords.get(record.identity()))) {
return false;
}
}
return true;
}
private Map<String, F> identityMap(List<F> fileRecords) {
// map creation using F.identity()
}
abstract List<D> fetchAllDBRecords();
abstract List<F> fetchAllFileRecords();
abstract boolean verify(D dbRec, F fileRec);
}
class UserVerifier extends AbstractVerificationHandler<DBUser, FileUser> {
List<DBUser> fetchAllDBRecords() {
// code omitted
}
List<FileUser> fetchAllFileRecords() {
// code omitted
}
boolean verify(DBUser dbuser, FileUser fileuser) {
// code omitted
// fields specific comparison with different names etc.
}
}
class DBUser implements Identity {
// code omitted
}
class FileUser implements Identity {
// code omitted
}
AbstractVerificationHandler
calls theverify(DBUser, FileUser)
method but it does not know anything about it because it is defined in the subclass. \$\endgroup\$