2
I have a Factory
what instance the PARSER
responsible for extracting information from a particular invoice format. To determine the invoice format I use regex. I loop every regex added to Map
and check if the regex is found within the text of that invoice, if it is found, then PARSER
responsible for extracting data from this invoice.
For that, I created one Map
of Class and String, where String is regex. It was necessary to use Class because I cannot instantiate this PARSER
before knowing if it really is he who will be the PARSER
responsible because there are some logics in each constructor PARSER
.
public class InvoiceParserFactory
{
private static final Logger logger = LoggerFactory.getLogger(InvoiceParserFactory.class);
private static Map<Class<? extends InvoiceParser>, String> map = new HashMap<>();
static {
map.put(xxx_PARSER.class, "regex_xxx");
map.put(yyy_PARSER.class, "regex_yyy");
map.put(zzz_PARSER.class, "regex_zzz");
//...
}
public static InvoiceParser getParser(InvoicePdfReader reader)
{
String invoiceText = reader.getText();
for (Map.Entry<Class<? extends InvoiceParser>, String> entry : map.entrySet()) {
Class<?> clazz = entry.getKey();
String regex = entry.getValue();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(invoiceText);
if (m.find()) {
try {
Constructor<?> constructor = clazz.getConstructor(String.class);
return (InvoiceParser) constructor.newInstance(invoiceText);
} catch (Exception e) {
logger.error("Can't instantiate parser.", e);
}
}
}
throw new InvoiceException("Can't find parser.");
}
}
Doubt
Is this the best practice for this purpose? Particularly I found a gambiarra. Any suggestions to improve/refactor the code? Maybe using Java 8 Features?
Problem
In the future, I will need beyond regex, to perform some other condition, then I would have to completely refactor this Factory to support that besides a regex, it is possible to use other logics to instantiate the PARSER
correct or something similar to this. What is the best practice in this case?
Personally, I didn’t think it was a scam. Of course it has limitations and is not the most beautiful code we have seen, but I believe you should think about these limitations when they really bother you (as in the case you mentioned). Let’s wait to see if someone proposes a better idea. For now I am thinking here of an alternative.
– Dherik