2

I have three request objects called Request1To,Request2To,Request3To. I want to have a method that takes in any of these TO's and return a response object. I have currently implemented like this

class Mapper{
     public ResponseTo mapRequest1(Request1To){

      }

     public ResponseTo mapRequest2(Request2To){

      }

    public ResponseTo mapRequest3(Request3To){

      }

}

Is there a better way to do this instead of creating a seperate method for each request object?

3 Answers 3

4

Take a look at Dozer and modelmapper. They are both excellent tools for mapping one object to another. I know that Dozer integrates with Spring. In Dozer your code will look something like this:

Mapper mapper = new DozerBeanMapper();
ResponseTo response = mapper.map(request, ResponseTo.class);

It's very powerful and very easy to use.

0

Not knowing more of what those objects are like... just make a Request interface they all implement. Then the mapRequest method will take in the interface instead of the concrete class.

1
  • mapping for each request object is different.I need to have an if condition inside the mapRequest method to find what the instance type is and then do mapping which i dont like.
    – mohanaki
    Dec 29, 2012 at 4:01
0
public interface CustomRequest {


 public ResponseTo convertResponseTo();


}


public class Request1To implements CustomRequest{

    public ResponseTo convertResponseTo(){

     // do the logic and return response

    }

 }


  public class Mapper {


   public ResponseTo mapRequest(CustomRequest request){

      return request.convertResponseTo();

  }
}
3
  • i dont want to have chained if conditions.
    – mohanaki
    Dec 29, 2012 at 4:02
  • I changed my Answer check it
    – someone
    Dec 29, 2012 at 4:09
  • I need to have the mapping logic in transferobject which i don't want to do.As having mapping logic in transfer object ties it to a particular response type.
    – mohanaki
    Dec 29, 2012 at 4:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.