views:

264

answers:

2

I'm revising code I did not write that uses JavaMail, and having a little trouble understanding why the JavaMail API is designed the way it is. I have the feeling that if I understood, I could be doing a better job.

We call:

transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);

So why is Eclipse warning me that this:

transport.send(message, message.getAllRecipients());

is a call to a static method?

Why am I getting a Transport object and providing settings that are specific to it if I can't use that object to send the message? How does the Transport class even know what server and other settings to use to send the message? It's working fine, which is hard to believe. What if I had instantiated Transport objects for two different servers; how would it know which one to use?

In the course of writing this question, I've discovered that I should really be calling:

transport.sendMessage(message, message.getAllRecipients());

So what is the purpose of the static Transport.send() method? Is this just poor design, or is there a reason it is this way?

+3  A: 

The javadoc says:

Send is a static method that creates and manages its own connection. Any connection associated with any Transport instance used to invoke this method is ignored and not used. This method should only be invoked using the form Transport.send(msg);, and should never be invoked using an instance variable.

And yes probably, the design is not good

stacker
+5  A: 

Transport.send() is basically a convenience method. Yes, if you're managing your own Transport instance, call sendMessage().

I'm not sure I consider it bad design, since frequently you don't care to manage the details of sending and monitoring transport. Crack open the send() method to see what it does for you. Other ways of naming or placing this method could be marginally better, maybe.

Sean Owen