Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help to create a generic class to avoid code duplication

I have a simple problem try to stay DRY using Appengine.

The 2 functions below are identical except for the object sent as parameter. In reality I have 15 functions like this. I am try to find a way to create a super class or a generic to achieve 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 cannot use generics since generics don't support T.class.

Any good suggestion how to do this w/o duplicating?

Thank you. Daniel

like image 601
supercobra Avatar asked Jun 24 '26 23:06

supercobra


1 Answers

You don't need generics for this; use thing.getClass():

public void deleteRecord(Object thing) {
    ...
    Object o = pm.getObjectById(thing.getClass(), s.getId());
    ...
}

(you should add a null-check in there just in case the parameter passed in was null)

[Note: I changed my answer just after I posted it when I realized you don't need generics here...]

like image 180
Scott Stanchfield Avatar answered Jun 27 '26 11:06

Scott Stanchfield