Core Java

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.
 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Steve Hanson
Steve Hanson
10 years ago

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
ohgodkillmenow
10 years ago
Reply to  Steve Hanson

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
comrad
10 years ago
Reply to  Steve Hanson

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.

ARC
ARC
8 years ago
Reply to  comrad

Interesting – Do you clarifying with an example? Thanks.

Karl Isenberg
10 years ago

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.

Back to top button