vendredi 25 janvier 2019

Duplicate code refactoring in Java with patterns

This isn't dropwizard specific and more so on Java but here it goes.

So I have two resources in Dropwizard CustomerResource.java ApiResource.java In CustomerResource.java there is a createCustomer method which basically creates a new customer. Now the ApiResource.java will also be creating a new customer when a third party invokes a method inside of it. So this got me thinking about duplicate code and the best way to resolve this. I have few approaches in mind but first here are the classes for better clarity.

@Path("/internal")        
public class CustomerResource{

    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI

    public Response Create(@internalAuth CustomerPojo customerPojo) {

    //logic to validate customerpojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}



    public class ApiResource{
    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI
    @Path("/external")
    public Response Create(@ExternalAuth PartialCustomerPojo partialCustomerPojo) {

    //logic to validate PartialCustomerpojo
    //supplement partialCustomerPojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}

So two main differences are that how the endpoint is called (authentication) and the payload provided.

Some ways I thought about how to remove duplicate code.

Create a new concrete class that takes common from both and each of these method instantiate a new class like this.

    public class CommonClass{
    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI

    public boolean Create (CommonPojo commonPojo) {

    //logic to validate customerPojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}

And now inside CustomerResource.java and ApiResource.java I simply do this.

CommonClass commonClass = new CommonClass(dbDao, api);
//create a new instance customerPojo or CommonPojo and call 

commonClass.create(customerPojo);

Does this sound like a good strategy? or are there any other best practice around it? And no these two methods can't be inside same class either. Any best practice will be appreciated. thank you.

Aucun commentaire:

Enregistrer un commentaire