# Monday, 18 January 2010

Apex is a programming language supported by the Force.com platform.

A fluent interface is a way of implementing an object oriented API in a way that aims to provide for more readable code.

An example of a fluent interface looks like:

Contact c = new Contact();
ITransaction trx = new FluentTransaction()
		.Initialize(c, 5.0)
		.Validate()
		.Execute()
		.Log()
		.Finish();

Transactions are a good use case for implementing a fluent interface because they often execute the repeated steps of initializing and validating input values, executing, and logging data. An API designer can expressly define these methods in an interface using Apex (very similar to Java and C# interfaces). When implementing a transaction object, the compiler will check to ensure the proper interfaces are implemented.

A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call. Generally, the context is defined through the return value of a called method self referential, where the new context is equivalent to the last context.

public class MethodChaining {
	
	public interface ITransaction{		
		ITransaction Initialize(Contact c, double d);
		ITransaction Validate();
		ITransaction Execute();		
		ITransaction Log();
		ITransaction Finish();
		boolean IsValid();
		boolean IsSuccessful();
	}
	
	public class FluentTransaction implements ITransaction{
		private Contact m_contact;
		private double m_amount;
		private boolean m_isSuccessful = false;		
		private boolean m_isValid = false;
		
		public ITransaction Initialize(Contact c, double d){
			m_contact = c;
			m_amount = d;
			return this;
		}
		
		public ITransaction Validate(){
			//Validate the m_contact and m_amount inputs
			//Setting this to false will instruct other execution chain methods to halt
			m_isValid = true; 
			return this;
		}
		
		public ITransaction Execute(){
			if(IsValid()){
				// Execute the transaction here
				m_isSuccessful = true;
			}
			return this;
		}
				
		public ITransaction Log(){
			if(IsValid()){
				//Add any transaction audit logging here
			}
			return this;
		}
		
		public ITransaction Finish(){
			if(IsValid()){
				//Finalize method. Manage any required cleanup
			}
			return this;
		}
		
		public boolean IsValid(){
			return m_isValid;
		}
				
		public boolean IsSuccessful(){
			return m_isSuccessful;
		}		
	}
	
	public MethodChaining(){
		Contact c = new Contact();
		ITransaction trx = new FluentTransaction()
			.Initialize(c, 5.0)
			.Validate()
			.Execute()
			.Log()
			.Finish();
		
		if(trx.IsSuccessful()){
			//Do something
		}
		else{
			//Do something else
		}
	}
}