Multiple methods, identical content

So, I'm working on old code (written years ago) and I saw that I think this is an opportunity to improve it. But I need to point out why I want to change the existing code, and you need a more reasonable reason: "you shouldn't duplicate code".

So here's the problem. We have a MessageSender class to send JMS messages to several different queues. But whoever wrote the code wrote the same method 11 times with the only difference that it's basically the name of the queue.

For example, the current code looks like this:

    public void publishToQueue1(final Object messageContent, final Map<String, Object> jmsHeaders,final Map<String, String> headers) throws JMSException {
    logger.debug("sending to queue1 - some message blah blah");
    publishMessage(esbJmsTemplate, queue1.getQueueName(), messageContent, jmsHeaders, headers);
}

public void publishToQueue2(final Object messageContent, final Map<String, Object> jmsHeaders,final Map<String, String> headers) throws JMSException {
    logger.debug("sending to queue2 - some message blah blah");
    publishMessage(jmsTemplate, queue2.getQueueName(), messageContent, jmsHeaders, headers);
}

public void publishToQueue3(final Object messageContent, final Map<String, Object> jmsHeaders,final Map<String, String> headers) throws JMSException {
    logger.debug("sending to queue3 - some message blah blah");
    publishMessage(jmsTemplate, queue3.getQueueName(), messageContent, jmsHeaders, headers);
}

public void publishToQueue4(final Object messageContent, final Map<String, Object> jmsHeaders,final Map<String, String> headers) throws JMSException {
    logger.debug("sending to queue4 - some message blah blah");
    publishMessage(jmsTemplate, queue4.getQueueName(), messageContent, jmsHeaders, headers);    
}

public void publishToQueue5(final Object messageContent, final Map<String, Object> jmsHeaders,final Map<String, String> headers) throws JMSException {
    logger.debug("sending to queue5 - some message blah blah");
    publishMessage(jmsTemplate, queue5.getQueueName(), messageContent, jmsHeaders, headers);
}

... more methods that look like this.. 
... and on..
... and on..
and on...

      

I would like to replace this with a method that looks more like this when the queue name is part of the parameter.

public class MessagePojo {
    private Object message content;
    private Map<String, Object> jmsHeaders;
    private Map<String, String> headers;
    private String queueName;
..setters and getters...
}

public void publishMessage(MessagePojo mpo) {
    publishMessage(mpo);
}

      

Can anyone suggest some design / boilerplate principle for moving from legacy code (multiple identical techniques) other than DRI (don't repeat yourself)?

+3


source to share





All Articles