Train Wreck Pattern

Well, this might not be a good pattern, and will definitely have pitfalls, but the first look was very much interesting for me. 🙂

public class TrainWreckPattern {
  public static void main(String[] args) {
    new Mailer()
    .subject("Some subject")
    .body("Some content")


class Mailer{
  public Mailer to(String address){
    System.out.println("To: "+address);
    return this;
  public Mailer from(String address){
    System.out.println("From: "+address);
    return this;
  public Mailer subject(String sub){
    System.out.println("Subject: "+sub);
    return this;
  public Mailer body(String body){
    System.out.println("Body: "+body);
    return this;
  public void send(){
    System.out.println("Sending ...");

This code effectively removes the unnecessary setter methods. Though all the methods are set methods, it in turn returns the current object after setting the attribute. A single line, and all setter methods are called. And in fact in the above example the main operation of sending is also done on the same line of code. Interesting, isn’t it. Well I do not know whether this is an officially recognized pattern, but for me, who want to minimize the coding, this pattern seems to be too much interesting.

That’t it guys. Happy Coding… 🙂


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: