Wednesday, February 6, 2008

Fluent Problem Solving by Elimination

Many problems lend themselves to a solution through a process of elimination. These include the selection of scientific hypothesis, technical troubleshooting, medical diagnosis, etc. I have written a small framework to help solve this class of problems. Additionally, I made a fluent interface to create constraint rules. You can download it from the code samples section.

I am planning on creating a few examples in the near future to show it off, but for this post I just want to give a sneak peek at a couple of lines of Java code that uses it. This comes from a test that categorizes an animal based on observable qualities. This is the definition of one constraint rule that allows the system to know that no mammals have scales or feathers.

constraint = when(skin).is(scaley).or(skin).is(feathery).then(animalType).isNot(mammal);

Here is another that tells the system that only bats have both fur and wings:

constraint = when(skin).is(furry).and(phalanx).is(wings).then(animal).is(bat);

Sunday, January 20, 2008

Language Use Cases

Imagine that you are the customer for a new programming language. What three use cases would be most important to you and why?

Saturday, January 12, 2008

Searching for more Fluent API patterns for Java

Previous posts cover three patterns commonly seen in Fluent APIs in Java.
  1. Method Chaining
  2. Nested Interfaces
  3. Fluent Builder
So far these are the only Fluent patterns that I have seen used successfully in Java. Does anyone have any examples of Fluent APIs in Java that don't use one of these techniques?

Fluent API pattern: Method Chaining

Method Chaining is the simplest and most common pattern for creating Fluent APIs. A great example is in the Binder class in Guice. It allows you to chain methods one after another in a way that describes the desired results. Here is an example from the Guice User's Guide:

binder.bind(Service.class).to(ServiceImpl.class).in(Scopes.SINGLETON);

The simplest implementation of method chaining can be seen in the Java StringBuffer where the 'append' method returns a reference to itself. This is not exactly Fluent since it does not resemble a natural language sentence, but it works the same way.

This can also be seen in an example from a previous post that uses the CustomerCreator:

Customer customer = createCustomer.named("Bob").that(bought.item(CompactDisc).on("02/17/2006"));

The method 'named' returns another instance of a CustomerCreator such that you can chain the 'that' method off of it. Per usual, I strongly encourage you to download the full example source and play with it to see how these Fluent API pattern can be used in conjunction.