Please, any ideas on how to refactor this java code so I don't have to repeat those code blocks 3 (or more) times?
Integer id = null;
try {
id = (Integer)extradata.get("id");
}
catch(Exception e) {
logger.error(e);
}
if (id == null) {
logger.error("no id set");
task.setStatus(Status.ERROR);
DBService.updateTaskStatus(conn, false, task);
conn.commit();
return;
}
String name = null;
try {
name = (String)extradata.get("name");
}
catch(Exception e) {
logger.error(e);
}
if (name == null) {
logger.error("no name set");
task.setStatus(Status.ERROR);
DBService.updateTaskStatus(conn, false, task);
conn.commit();
return;
}
String city = null;
try {
city = (String)extradata.get("city");
}
catch(Exception e) {
logger.error(e);
}
if (city == null) {
logger.error("no city set");
task.setStatus(Status.ERROR);
DBService.updateTaskStatus(conn, false, task);
conn.commit();
return;
}
You can use a static generic method:
private static final <T> T getValue(Map<String, Object> extradata, String key, Class<T> clazz) {
Object val = extradata.get(key);
if (val == null) {
handleNullVariable("name");
return null;
}
return clazz.cast(val);
}
Then you can call it with:
Integer id = getValue(extradata, "id", Integer.class);
String name = getValue(extradata, "name", String.class);
Integer id = null;
String name = null;
String city = null;
try {
id = (Integer)extradata.get("id");
name = (String)extradata.get("name");
city = (String)extradata.get("city");
catch(Exception e) {
logger.error(e);
}
if (id == null || name == null || city == null) {
String msg = (id == null ? "id" : name == null ? "name" : "city");
logger.error("no "+msg+" set");
task.setStatus(Status.ERROR);
DBService.updateTaskStatus(conn, false, task);
conn.commit();
return;
}
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