Skip to content

Email Builder Example

UnquietCode edited this page May 13, 2012 · 11 revisions

The email builder showcases a few important concepts, including dynamic methods and minimum invocations. In the example, the user can build an email message by specifying the subject, body, recipient(s), etc. At least one sender and one recipient must be specified, though any number can be added. There is one last() method which is send(), and this allows us to exit the descriptor to send the email message.

The descriptor looks like this:

	DescriptorGenerator.create(new DescriptorHelperImpl())
		.setPackage("unquietcode.tools.flapi.examples.email.builder")
		.setStartingMethodName("compose")
		.setDescriptorName("Email")
		.setReturnType(EmailMessage.class)

		.addMethod("setSubject(String subject)").once()
		.addMethod("addRecipient(String emailAddress)").atLeast(1)
		.addMethod("setSender(String emailAddress)").atLeast(1)
		.addMethod("addCC(String emailAddress)").any()
		.addMethod("addBCC(String emailAddress)").any()
		.addMethod("setBody(String text)").once()
		.addMethod("addAttachment(java.io.File file)").any()
		.addMethod("send()").last()
	.build()

The methods can be mapped to the following table listing their allowed invocations in the builder:

Method Name Invocations
setSubject(...) [0,1]
addRecipient(...) [1,∞)
setSender(...) [1,∞)
addCC(...) [0,∞)
addBCC(...) [0,∞)
setBody(...) [0,1]
addAttachment(...) [0,∞)
(where ∞ is, for our purposes, MAX_INT)

After generating the builder classes, we can use it like this:

EmailMessage message = EmailGenerator.compose(new EmailHelperImpl())
	.setSender("iamthewalrus@hotmail.com")
	.addRecipient("unclebob@unquietcode.com")
	.setSubject("Has you seen my bucket?")
	.setBody("Dear sir,\nI was wondering, have you seen my bucket? It is small, metallic, somewhat used, " +
			 "and slightly smells of fish. Please let me know if you have or do ever see it.\n\nThanks!")
.send();
Clone this wiki locally