Skip to content

Email Builder Example

Benjamin Fagin edited this page Feb 6, 2013 · 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:

Descriptor builder = Flapi.builder()
	.setPackage("unquietcode.tools.flapi.examples.email.builder")
	.setStartingMethodName("compose")
	.setDescriptorName("Email")

	.addMethod("subject(String subject)").atMost(1)
	.addMethod("addRecipient(String emailAddress)").atLeast(1)
	.addMethod("sender(String emailAddress)").exactly(1)
	.addMethod("addCC(String emailAddress)").any()
	.addMethod("addBCC(String emailAddress)").any()
	.addMethod("body(String text)").atMost(1)
	.addMethod("addAttachment(java.io.File file)").any()
	.addMethod("send()").last(EmailMessage.class)
.build();

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

Method Name Invocations
subject(...) [0,1]
addRecipient(...) [1,∞)
sender(...) [1,1]
addCC(...) [0,∞)
addBCC(...) [0,∞)
body(...) [0,1]
addAttachment(...) [0,∞)
(where ∞ is, for our purposes, MAX_INT)

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

EmailMessage message = EmailGenerator.compose(new EmailHelperImpl())
	.sender("iamthewalrus@hotmail.com")
	.addRecipient("unclebob@unquietcode.com")
	.subject("Has you seen my bucket?")
	.body("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();

Note that if we failed to call either sender(...) or addRecipient(...) then when the send() method was called we would have triggered a MinimumInvocationsException. This is a result of using the atLeast(1) method qualifier. Further, after calling sender(...) the method would no longer be present in the API. This behavior is immediately recognizable when using code completion.

The full example can be found here.

Clone this wiki locally