Search code examples
javaoopcoding-style

How do I abstract this correctly


I am in a dilemma here.

So, I have this Rest API that acts as a simplifying proxy between another API that consumes it and a SOAP API from an external provider.

In it, I have 4 methods corresponding to 4 Soap endpoints, which map data from the Rest request DTO-s to the Soap request DTO-s.

The 4 Rest request DTO-s have a CommonDto that contains some objects that all the requests have in common.

Some of the fields of this common REST request DTO can be nullable, and if that is the case, I have nullchecks in place so that I do not set the corresponding SOAP request fields at all, as that would make the SOAP request fail.

The 4 methods basically look like this:

public RestResponseObject1 method1(RestRequestObject1 rRO1){
   SoapRequestObject1 sRO1= new SoapRequestObject1();

   Object commonField1= rR01.getCommonField1();//Object can be anything, BigDecimal, String, int,etc.
   if(commonField1!=null){
       sRO1.setCommonField1(commonField1);
   }

   BigDecimal commonField2= rR01.getCommonField2();
   if(commonField2!=null){
       sRO1.setCommonField2(commonField2.intValue());
   }

  //etc....

  return Mapper.map(soapService.doSoapMethod1(sRO1);
}

this method is 4 times repeated, with different RestRequestObjects, RestResponseObjects, and SoapRequestObjects, but the commonfields types don't change between them.

My question is, how can I abstract the nullchecks so that I do not repeat them for each method so that my code is cleaner? Be aware that I DO NOT have the option to do anything with the Soap request objects since they are auto-generated through Swagger/OpenApi


Solution

  • Or to build up on the Previous answer, make it more generic so it would work for other request objects as well

    private <T, E> void setIfNotNull(E setterObject, BiConsumer<E, T> setter, T value) {
       if (value != null) {
           setter.accept(setterObject, value);
       }
    }
    

    With this you can now call

    setIfNotNull(sRO1, sRO1::setCommonField1, rR01.getCommonField1());