Train Wreck Pattern – A much improved implementation in Java 8

Venkat Subramaniam at a talk today mentioned about Cascade Method pattern or Train Wreck pattern which looks something like:
 
 
 
 
 
 
 
 
 

>someObject.method1().method2().method3().finalResult()

Few might associate this with the builder pattern, but its not the same. Anyways lets have a look at an example for this in Java with out the use of lambda expression:

public class TrainWreckPattern {
  public static void main(String[] args) {
    new Mailer()
    .to("to@example.com")
    .from("from@exmaple.com")
    .subject("Some subject")
    .body("Some content")
    .send();

  }
}

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 ..."); 
  }
}

I have taken the same example which Venkat Subramaniam took in his talk. In the above code I have a Mailer class which accepts a series of values namely: to, from, subject and a body and then sends the mail. Pretty simple right? But there is some problem associated with this: One doesn’t know what to do with the Mailer object once it has finished sending the mail. Can it be reused to send another mail? Or should it be held to know the status of email sent? This is not known from the code above and lot of times one cannot find this information in the documentation. What if we can restrict the scope of the Mailer object within some block so that one cannot use it once its finished its operation?

Java 8 provides an excellent mechanism to achieve this using Lambda expressions. lets look at how it can be done:

public class TrainWreckPatternLambda {

  public static void main(String[] args) {
    Mailer.send( mailer -> {
      mailer.to("to@example.com")
            .from("from@exmaple.com")
            .subject("Some subject")
            .body("Some content");
    });
  }

}

class Mailer{

  private 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 static void send(Consumer<Mailer> mailerOperator){ 
    Mailer mailer = new Mailer();
    mailerOperator.accept(mailer);
    System.out.println("Sending ..."); 
  }
}

In the above implementation I have restricted the instantiation of the Mailer class to the send() method by making the constructor private. And then the send() method now accepts an implementation of Consumer interface which is a Single Abstract method class and can be represented by a Lambda expression. And in the main() method I pass a lambda expression which accepts a Mailer instance and then configures the mailer object before being used in the send() method.

The use of lambda expression has created a clear boundary for the use of the Mailer object and this way its much ore clearer for someone reading the code as to how the Mailer object has to be used.

Let me know if there is something more that I can improve in this example I have shared.
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

4 Responses to "Train Wreck Pattern – A much improved implementation in Java 8"

  1. Steve Hanson says:

    I enjoyed your article and think your solution is interesting. Though the API you described using lambdas seems to solve your problem, I feel like it is too complex for the average developer to easily know how to work with it. Even after lambdas gain popularity, the API still does not seem intuitive to me. I’m curious to hear your and others’ thoughts.

    • ohgodkillmenow says:

      Interesting == incoherent in this case. Lambdas have should have nothing to do with this–what’s really needed is segregation of DTO (mail) from the fluent DTO builder (mail builder) from the service (mailer). It’s amazing how often solid OOD skills are overlooked when people are blinded by shiny new language features.

    • comrad says:

      Software development is never easy. That’s why amateurs shouldn’t work on fixing their car’s breaks or work on the house’s electricity.

      Lambdas require some effort to get used to but you get cleaner and sharper code in return. But that’s the same with every new technology.

      But I agree, the api is a headturner, once you’ve worked with e.g. ruby or scala. But i am still happy to be able to use functional programming now in Java as well.

  2. Seems like a better solution to this particular problem would be to have an immutable Mail object with a builder and a separate Mailer service class that has send(Mail) with or without return object to handle the callback.

Leave a Reply


5 + two =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close