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.
 

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

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


nine − 2 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books