Java – helps create generic classes to avoid code duplication
I have a simple question. Try to use appengine to keep dry
The following two functions are the same except for the object sent as a parameter Actually, I have 15 such functions I'm trying to find a way to create a superclass or generic to do this
public void deleteRecord(Person s) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { Person p = pm.getObjectById(Person.class,s.getId()); pm.deletePersistent(p); } finally { pm.close(); } }
and
public void deleteRecord(Product s) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { Product p = pm.getObjectById(Product.class,s.getId()); pm.deletePersistent(p); } finally { pm.close(); } }
Unfortunately, it seems that I can't use generics because generics don't support t.class
Any good suggestions on how to do this without copying?
thank you. Daniel
Solution
Doing is a good principle Kiss is the same; -)
public void deleteRecord(Class classOfProduct,Object id) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { Object p = pm.getObjectById(classOfProduct,id); pm.deletePersistent(p); } finally { pm.close(); } }
This will be called, for example:
theObject.deleteRecord(Person.class,s.getId()); theObject.deleteRecord(Product.class,s.getId());
Since this is a void method and PersistenceManager doesn't seem to apply to generic types, I recommend avoiding generics If applicable, this method has additional benefits. You do not need to modify the type hierarchy of product, person, etc
The downside is that if you call this method from multiple places, there may be many changes to the signature - but it's easy for the compiler to find out how long it takes