I'm a fan of static methods in java for eg in Util-classes. But among some colleagues I have met some arguments that a static method should never use external resources. But none could explain why it should be bad or even dangerous. The only reason I have found is that it may be hard to mock that external resource during test. But is that really the only reason?
Below I got an example of a static method. I would love to understand why it should be a bad approach to use it with static.
public class JmsUtil {
public static String sendBytesMessage(byte[] messageBytes) throws JMSException, NamingException {
String jmsMessageID = null;
Connection connection = null;
try {
Context context = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ourfactory");
Queue queue = (Queue) context.lookup("ourqueue");
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeBytes(messageBytes);
messageProducer.send(bytesMessage);
jmsMessageID = bytesMessage.getJMSMessageID();
} finally {
if (connection != null) {
connection.close();
}
}
return jmsMessageID;
}
}
Best regards