我是Java中静态方法的粉丝,例如在Util-classes中。但在一些同事中,我遇到过一些静态方法不应该使用外部资源的论点。但没有人能解释为什么它应该是坏的甚至是危险的。我发现的唯一原因是在测试过程中可能很难嘲笑外部资源。但是,这真的是唯一的原因吗?为什么不使用静态方法来处理外部资源?
下面我有一个静态方法的例子。我想知道为什么它应该是一个不好的方法来使用它与静态。
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;
}
}
问候
静态方法没有错。这取决于你需要什么。有很多很棒的工具,比如apache common,实际上有很多静态方法的StringUtils。如果你想嘲笑静态的东西,你可以使用Powermock。无论如何,这个问题对我来说似乎有些偏离主题,因为这更像是一个基于意见的事情。 –
在您的示例代码中'sendBytesMessage'没有标记为'static' – tommyO
静态方法使得在测试中模拟出外部资源变得困难(或不可能,如果您不想使用类似PowerMockito的东西)。也许阅读[静态方法是可测试性的死亡](http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/)。 “ –