Showing posts with label pattern. Show all posts
Showing posts with label pattern. Show all posts

Tuesday, 29 April 2014

Fluent Builder method ordering

Classic simple fluent builder usually suffers from some annoyances.

Let's look a this example:
ComplexClass cc = ComplexClass.Builder()
  .addThis(42).setThat("I'm that").addSomethingOther("I'm other")
  .addYetAnother("yet yet yet").mixPudding(true).setChickenFeedingDevice(device)
  .addThis(99).withTimeout(5000).setThat("I'm another that").build()
Disregarding silly and inconsistent method naming...
  • large number of builder methods confuse user
  • builder method can be mistakenly called multiple times

Having way to enforce order into method chaining will allow to build something more like wizzard or workflow which wiil simplify Builder usage greatly.

Let's introduce some interfaces according following rules
  • Any interface declares only subset of Builder methods
  • Interface method return value is another interface instead of Builder instance
  • Builder itself implements all interfaces

Together this basicaly forms very simple example of formal grammar where order in interface chaining represents production rules

To demonstrate idea just described, I built Selenium2/WebDriver WaitBuilder. It uses WbBegin interface as initial building point, WbAnd interface allowing to add multiple multiple conditions and finaly WbEnd with .seconds(int seconds) method instead of traditional .build().

Selenium has WebDriverWait class allowing conditional waits, which is very useful for testing pages, where elements appear dynamicaly or to perform assertion of Post/Redirect/Get (redirect after form submission) in time-boxed manner. SeleniumWaitBuilder allows to combine multiple conditions together.

It enables to write such cool chains such as...
//pass test if "results-table" element will appear in 5 seconds, fail otherwise
SeleniumWaitBuilder.with(driver)
 .passOn().element(By.id("results-table")).seconds(5);

//pass test if title become "Example Domain" and in 5 seconds or fail immediately if it happen to contain "error" string
SeleniumWaitBuilder.with(driver).passOn()
  .title().equals("Example Domain")
 .and().failOn()
  .title().contains("error")
 .seconds(5);

SeleniumWaitBuilder.with(driver).passOn()
  .title().endsWith("Example Domain")
  .element(By.id("result-table"))
 .and().failOn()
  .title().contains("error")
  .url().contains("/500")
 .seconds(5);

And finally, hero of today's blog post - mighty SeleniumWaitBuilder itself!

I admit that this is overkill for most of the builders but still, it is neat...

Happy contitional waiting!

Thursday, 28 November 2013

Generic throws

Suprisingly few developers really master Java generics in their full extent. As apparently not being one of them, generic throws feature surprised me lately.

Following code snippet shows the idea - generic <X extends Exception> is used in throws part of go() method. Implementing class defines Exception subclass that will be allowed to be thrown.

import java.io.FileNotFoundException;
interface Something<X extends Exception> {
  
 public abstract void go() throws X;
  
}
 
class SomethingImpl implements Something<FileNotFoundException> {
  
 public void go() throws FileNotFoundException {
  throw new FileNotFoundException("Yeah! Not found!");
 }
}

Interesting trick, but how can this be useful? Well, for example, you can pimp Strategy pattern with cunning Exception passing/handling!

In Strategy pattern, you basicaly have two choices how to deal with exceptions
  • Add throws Exception on both strategy interface and context method to pass every exception back to client - especially poor choice
  • Add throws Exception on strategy interface method, catch it inside context and rethrow it wrapped inside RuntimeExcetpion back to client - usual solution, but it mixes strategy and context exceptions together
But with generic throws, aditional options are available.

This is interface allowing Client to implement his own LoaderStrategy and it also allows him to choose Exception which can be thrown from his LoaderStrategy via generic throws X

/**
 * Strategy interface - To be implemented by client
 */
interface LoaderStrategy<X extends Exception> {

 public String load(long id) throws X;

}

And this is simple Context using LoaderStrategy interface. It is also passing chosen exceptions from strategy back to client, again via generic throws X

/**
 * Context using LoaderStrategy, passing selected exceptions (X)
 */
class StrategyContext {

 public <X extends Exception> void perform(LoaderStrategy<X> oader) throws X {

  long resourceId = getIdFromSomewhere();

  String data = loader.load(resourceId); //throws X - don't have to hadle exception here

  try {
   sendDataToRemoteSystem(data);
  } catch (RemoteException rx) {
   //Other checked Exception must be wrapped inside ContextException 
   throw new ContextException("Failed to send data for resourceId " + resourceId, rx);
  }
 }

 private long getIdFromSomewhere() {
  return System.currentTimeMillis(); //CurrentTimeMillis is best id ever!
 }

 private void sendDataToRemoteSystem(String data) throws RemoteException {
  //invoke some remoting operation here...
 }
}

/**
 * Context exception wrapper - delivers other then LoaderStrategy exceptions to client 
 */
class ContextException extends RuntimeException {

 public ContextException(String string, Exception cause) {
  super(string, cause);
 }
}

Use case 1 - Passing checked Exceptions

This is client's LoaderStrategy implementation. It throws IOException
/**
 * Client provided LoaderStrategy implementation throwing IOException
 */
class ReaderLoader implements LoaderStrategy<IOException> {

 private Reader reader;

 public ReaderLoader(Reader reader) {
  this.reader = reader;
 }

 public String load(long id) throws IOException {
  String sid = String.valueOf(id);
  BufferedReader br = new BufferedReader(reader);
  String line = null;
  while ((line = br.readLine()) != null) {
   if (line.startsWith(sid)) {
    return line;
   }
  }
  return null;
 }
}
Then IOException is propagated back into client code to be handeled here
 StrategyContext context = new StrategyContext();

 ReaderLoader readerLoader = new ReaderLoader(new StringReader("Blah! Blah! Blah!"));
 try {
  context.perform(readerLoader);
 } catch (IOException iox) {
  //ReaderLoader thrown IOException is propagated through StrategyContext and delivered here
 } catch (ContextException cx) {
  //StrategyContext thrown exception wrapper - All sorts of NON ReaderLoader originated Exceptions
  Throwable cause = cx.getCause();
 }
This does not brings much value, but in client code we can easily distinguish our ReaderLoader originated exceptions from Context originated ones and handle them differently. Simple two catch clauses.

Use case 2 - Customized checked Exceptions

Client also provides custom Exception he want to be thrown from his Strategy and propagated through StrategyContext back to client
/**
 * Client provided custom Exception
 */
class InvalidRecordCountException extends Exception {

 private long recordId;

 public InvalidRecordCountException(long recordId, String message) {
  super(message);
  this.recordId = recordId;
 }

 public InvalidRecordCountException(long recordId, SQLException exception) {
  super(exception);
  this.recordId = recordId;
 }

 public long getRecordId() {
  return recordId;
 }
}

/**
 * Client provided LoaderStrategy implementation throwing custom InvalidRecordCountException
 */
class JdbcLoader implements LoaderStrategy<InvalidRecordCountException> {

 private DataSource dataSource;

 private String select;

 public JdbcLoader(DataSource dataSource, String select) {
  this.dataSource = dataSource;
  this.select = select;
 }

 @Override
 public String load(long id) throws InvalidRecordCountException {
  Connection connection = null;
  PreparedStatement statement = null;
  ResultSet resultSet = null;
  try {
   connection = dataSource.getConnection();
   statement = connection.prepareStatement(select);
   statement.setLong(1, id);
   resultSet = statement.executeQuery();
   if (resultSet.next()) {
    String string = resultSet.getString(1);
    if (resultSet.next()) {
     //here we go...
     throw new InvalidRecordCountException(id, "Too many somethings in somewhere!");
    }
    return string;
   } else {
    //here we go...
    throw new InvalidRecordCountException(id, "Not a single something in somewhere!");
   }
  } catch (SQLException sqlx) {
   //here we go...
   throw new InvalidRecordCountException(id, sqlx);
  } finally {
   //TODO close resultSet, statement, connection
  }

 }
}
Then SQLExceptions are handled while InvalidRecordCountException propagated
 StrategyContext context = new StrategyContext();

 DataSource dataSource = null; //get it from somewhere
 JdbcLoader jdbcLoader = new JdbcLoader(dataSource, "SELECT something FROM somewhere WHERE column = ?");
 try {
  context.perform(jdbcLoader);
 } catch (InvalidRecordCountException ircx) {
  //JdbcLoader thrown InvalidRecordCountException is propagated through StrategyContext and delivered here
  long badRecordId = ircx.getRecordId(); //we can take some action when knowing failing record id
 } catch (ContextException cx) {
  //StrategyContext thrown exception wrapper - SQLException will be cause propably...
  Throwable cause = cx.getCause();
 }
Now we can easily pass additional error information inside custom exception.

Well, I understand that nobody loves to write lots of single purpose exceptions, but adopting "generic throws idiom" quite increases exception reusability.

All used code can by found in kitchensink repository

Thursday, 18 April 2013

Building Fluent Builder

Recently I've rediscovered another wheel again, but this one is pretty interesting I think...

Simple Fluent Builder

Builder is rather simple desing pattern. It accumulates bunch of values and then uses them to construct some complex product.

Fluent builder is a builder with fluent interface. That means it returns reference to self from every method (except the build() method that returns product) so it allows method chaining.
Nice and simple example is StringBuilder from java standard library.

String hello = new StringBuilder()
  .append("h").append("e").append("l").append("l").append("o")
  .toString();

Generic getThis() trick

When Builder is single standalone class, using return this is dead simple solution, but when inheritance comes into play, builder base class methods cannot return this, because we need concrete builder to be returned to allow method chaining.

Solution is the getThis() trick, that allows to return reference to concrete builder even from base class that builder is extending. The price is that every concrete builder must implement getThis() method.

Here is a nice article with some background and explanation

Generic parent trick

I've found another slightly different scenario, when similar generic trick can be used. It employs two builders and uses generic parent (instead of generic self) to keep track of builders used in chaining. It is quite simple JSON builder.

JSON message is built on two structures: object and array, therefore we will have two concrete builders working together. We don't want builder user to be confused by offering object building methods to him when he constructs array and contrariwise. When user completes constructing array or object, previous builder must be restored and returned to user.

This builder completely prevents user from making wrong method call at any point of building.

JSR-353 - JSON-P

Brand new Java API for JSON processing is going to be part of the upcoming JEE 7 specification also contains JSON builder.
Surprisinly to me they came with simplest builder that is throwing exception when user calls object/array builder method out of correct object/array building context.
For example this code
JsonGenerator jg = javax.json.Json.createGenerator(System.out);
jg.writeStartObject().write("array_element").writeEnd();
executed will throw
javax.json.stream.JsonGenerationException: write(String) can only be called in array context
Very error prone API indeed! I've filed improvement into Jira, but since JSR already passed the Final Approval Ballot, I guess there is no hope.