I am developing an application, where I have to send lots of emails for user account creations, validation, invites etc.
I have implemented a static class EMailUtil which has different methods like
public static void sendInvite(from, to, Subject){...}
public static void sendVerificationCode(from, to, subject, code){...}
Afterwards, I converted that class to a singleton. I was wondering if there is a way I can improve my approach here. What other pattern I could use here and what is the best approach to implement this utility class?
4
Ok, here’s one suggestion.
First of all, you should get rid of repeating parameters (from, to, subject etc) and methods (sendInvite, sendVerificationCode etc).
To achieve that you could start with defining an EMail-class holding the parameters as attributes. This is quite a standard approach when facing repeating parameters. Now all invitations and verifications and such would be just instances of EMail and all EMails could be send using only one send-method. Thus you would also get rid of the repeating methods.
EMail could be subclassed or it could provide factory methods for creating all kinds of messages. So either
EMail verificationMessage = new VerificationEMail(recipient, verificationCode);
or
EMail verificationMessage = EMail.createVerificationMessage(recipient, verificationCode);
I’d choose the latter approach if it does not lead to an overly bloated EMail class.
What goes into from and subject fields of a message should probably be decided in the method that’s creating a message of a certain type. All verification messages should probably have a similar title etc.
After defining the structure of the messages you only need some kind of dispatcher or such to send them:
EMailDispatcher dispatcher = new EMailDispatcher();
dispatcher.send(someMessage);
Dispatcher could have only one method to send messages:
public void send(EMail mail);
I’d try to avoid having a static send method like your EMailUtil has. Static methods are hard to replace for unit tests and otherwise. You don’t want to get thousands of actual emails sent every time automated tests run.
Now, if you’re using JavaMail-API, then it already has a Message
-class. However it could prove useful to have your own message class to define the contents and types of messages your application needs and have the dispatcher deal with the more technical Java-API.
0