SOA Best Practices - Simplifying ServiceFacade

In this article you will learn about Service Oriented Architecture(SOA) and how to simplify ServiceFacade.

A common practice observed during creating a service is heavy usage of ServiceFacade. By Façade definition, A facade is an object that provides a simplified interface to a larger body of code, such as a class library. In this post I’ll be discussing about the challenge that are faced with ServiceFacade classes while working on SOA (Service Oriented Architecture).

Note: In this article we’ll be using WCF service contracts for sampling. The language is C# and code editing tool used is Visual studio 2013.

Let’s take a look at the high level design of Façade pattern.

high level design of Facade pattern

Usually when the services are created we only concentrate on developing the server side functionality without thinking of fact that how service could grow in future because of the business. A simple example, creating a service that manages products of an eCommerce site. Suppose the product service provides the following operations:

  • Create a product
  • Delete a product
  • Edit product
  • GetProduct
  • GetProductsList
  • Search product
  • Miscellaneous other operation

Now, let’s take a look at the service contract. I’ll be taking the sample of WCF service contracts for demonstration,

  1. public interface IProductService  
  2. {  
  3.     [OperationContract]  
  4.     IEnumerable < Product > GetProductsList(Guid categoryId, int pageIndex, int pageSize);  
  5.     [OperationContract]  
  6.     Product Edit(Model.Product product);  
  7.     [OperationContract]  
  8.     Product Get(Guid productId);  
  9.     [OperationContract]  
  10.     Product Create(Model.Product product);  
  11.     [OperationContract]  
  12.     IEnumerable < Product > SearchProduct(SearchCriteria criteria);  
  13.     [OperationContract]  
  14.     void Delete(Guid productId);  
  15. }  
Let’s take a look at the usually seen implementation of above contract:
  1. public class ProductService: IProductService  
  2. {  
  3.     IRepository < Product > product;  
  4.     ILogger logger;  
  5.     InventoryService service;  
  6.     //...  
  7.     //...  
  8.     // And any other dependencies required to fulfill  
  9.     // operations requirement here.  
  10.     public IEnumerable < Product > GetProductsList(Guid categoryId, int pageIndex, int pageSize)  
  11.     {  
  12.         // A try..catch{} for error/exception handling  
  13.         // Check inventory step  
  14.         // Get inventory availabilities step  
  15.         // Prepare products lists step  
  16.         // ... bunch of other stuff.  
  17.         // Log, if required etc..   
  18.         // return the response.  
  19.     }  
  20.     public Product Edit(Product product)  
  21.     {  
  22.         // Actual core logic of Editing a product.  
  23.     }  
  24.     public Product Get(Guid productId)  
  25.     {  
  26.         // Actual core logic of Fetching a product.  
  27.     }  
  28.     public Product Create(Product product)  
  29.     {  
  30.         // Actual core logic of Adding a product.  
  31.     }  
  32.     public IEnumerable < Product > SearchProduct(SearchCriteria criteria)  
  33.     {  
  34.         // Actual core logic of Seraching products.  
  35.     }  
  36.     public void Delete(Guid productId)  
  37.     {  
  38.         // Actual core logic of Deleting a product.  
  39.     }  
  40. }  
This is Façade pattern in real life scenario. I would call it service façade since we are talking in context of SOA. When we look the above service façade sample, it seems fine, right? Unless the business decided to add/replace/remove/re-locate an operation to another service. Now think about removing the Get() method from Product contract to some other service contract. The whole logic written under Get() will be demolished or might not work when moved to another service contract. Why? Because it’s tightly coupled with Façade here.

The following figure illustrating the coupling of CoreLogic and ServiceContracts:

CoreLogic and ServiceContracts

Let’s take a look at the downside of such Facades in SOA especially on services side:

Architect’s point of view

The coupling of the core service logic to contracts and implementation resources can inhibit its evolution and negatively impact service consumers.

“When a service is subject to change either due to changes in the contract or in its underlying implementation, this core service logic can find itself extended and augmented to accommodate that change. As a result, the initial bundling of core service logic with contract-specific or implementation-specific processing logic can eventually result in design-time and runtime challenges.”
[Ref. SOA Design Patterns by Thomas Erl (Chapter 12)].

Developer’s point of view

 

  1. A huge bodied class carrying out all business logics (or core service logic).
  2. Class became larger and larger as more methods will get added.
  3. Hard to Unit test due to lengthy methods.
  4. A centralize place where multiple developers will be working on it fix bugs/adding new operations. Now you can imagine how this central place can easily be polluted with stuff.
  5. Bug prone!!! Fixing a bug could end up introducing multiple bugs also known as “Rebugging code”. See Fallacy of resue.

Considering both scenarios; ServiceFacades are problems and may become problem in future for maintenance so I decided to write this post as reference to developer seeking solution to this problem.

Solution approach

The problem can be solved by separating core logic from service contracts(façade) to separate self-operating entities. The following figure illustrates the idea of separating the Contracts from CoreLogic:

Contracts from CoreLogic

From implementation point of view let’s try to solve this problem using Command Pattern. 

Why command pattern?

A command can represent individual operation of service contract. Then we can use a dispatcher to invoke a particular command. Also the Core logic of individual operation can reside in commands. This is “An approach” to solve above problem.

Note: The implementation of CommandPattern that I’ll use in this post might differ from the samples given on various sources. Design patterns are Notion to use the power of Object Oriented world. Implementation can vary but it shouldn’t violate principles.

Simplifying ServiceFacade

The following figure shows the idea of using commands and redirecting each operation request to dedicated command via command dispatcher.

ServiceFacade

Now let’s go back to the code and create a new project which will consists of Commands representing each operation from Service Contract. So let’s create a class library project and name the project “ServiceOperations”. Well I just named it because “Naming is one of the hardest thing in computer programming world”.

Service Operation

In this project we have 3 project folders which I have created for separating the classes by their respective responsibilities.

  • Base – Consists of Abstract classes and interfaces.
  • Commands – Consists of all commands and command result(we’ll be discussing these two).
  • Handlers – Consists of Handlers which will execute the commands.

Now we’ll start adding commands with respect to operations from service contract. For sampling we’ll create a command for Get(Guid ProductId) operation from service contract. To start with we need some foundation classes to implement command pattern under Base folder.

BaseCommand

  1. /// <summary>  
  2. /// Each command would be dervied from Base command  
  3. /// </summary>  
  4. public abstract class BaseCommand  
  5. {  
  6.     /// <summary>  
  7.     /// Logical name to represent the command.  
  8.     /// [optional] and can be used for other pusposes like logging/error reporting etc.  
  9.     /// </summary>  
  10.     public string Name { getprotected set; }  
  11. }  
BaseCommandResult
  1. /// <summary>  
  2. /// Each command must have a result to send back.   
  3. /// Any command restul must inherit from this class.  
  4. /// </summary>  
  5. public abstract class BaseCommandResult  
  6. {  
  7.     /// <summary>  
  8.     /// Contains error details, if occurred during execution.  
  9.     /// </summary>  
  10.     public ErrorDetails Error { getset; }  
  11. }  
  12.   
  13. /// <summary>  
  14. /// Represent error details happened during command execution.  
  15. /// </summary>  
  16. public class ErrorDetails  
  17. {  
  18.     /// <summary>  
  19.     /// Error code, For production level debugging purpose(representing technical issue type).  
  20.     /// </summary>  
  21.     public int Code { getset; }  
  22.    
  23.     /// <summary>  
  24.     /// Application friendly error message.  
  25.     /// </summary>  
  26.     public string Message { getset; }  
  27. }  
BaseCommandHandler – Design of this class is really important as each command handler should know the command and its return type. Also common error handling etc. will be done in base class only. As I mentioned above the implementation of command pattern might differ. But first it should fulfill the purpose of business while following SOLID principles.
  1. /// <summary>  
  2. /// A marker interface for CommandHandlers.  
  3. /// </summary>  
  4. public interface ICommandHandler<TCommand, TResult>  
  5. {  
  6.     TResult Execute(TCommand command);  
  7. }  
  8.    
  9. /// <summary>  
  10. /// Each command handler must be dervied from this class.  
  11. /// </summary>  
  12. public abstract class BaseCommandHandler<TCommand, TResult> : ICommandHandler<TCommand, TResult>  
  13. {  
  14.     /// <summary>  
  15.     /// Executes the command logic in safe execution context.  
  16.     /// </summary>  
  17.     public TResult Execute(TCommand command)  
  18.     {  
  19.         try  
  20.         {  
  21.             return this.ExecuteCore(command);  
  22.         }  
  23.         catch(Exception exception)  
  24.         {  
  25.             this.HandleException(exception);  
  26.    
  27.             return this.GenerateFailureResponse();  
  28.         }  
  29.     }  
  30.    
  31.     /// <summary>  
  32.     /// Consists of actual logic to process any command.  
  33.     /// </summary>  
  34.     protected abstract TResult ExecuteCore(TCommand command);  
  35.    
  36.     /// <summary>  
  37.     /// Consists of dervied handler specific strategy to respond to   
  38.     /// any error occurred during execution.  
  39.     /// </summary>  
  40.     protected abstract TResult GenerateFailureResponse();  
  41.    
  42.     /// <summary>  
  43.     /// Method detailing the handling of exception.  
  44.     /// Override this method to have CommandHandler specific error handling.  
  45.     /// </summary>  
  46.     protected virtual void HandleException(Exception exception)  
  47.     {  
  48.         // do logging  
  49.     }  
  50. }  
Add a new class under the folder commands and name it GetProductCommand and GetProductCommandResult. Design the classes like the following:
  1. /// <summary>  
  2. /// Contains arguments and information required to process Get product request.  
  3. /// </summary>  
  4. public class GetProductCommand : BaseCommand  
  5. {  
  6.     /// <summary>  
  7.     /// Product Id  
  8.     /// </summary>  
  9.     public Guid ProductId { getset; }  
  10.    
  11.     public GetProductCommand(Guid productId)  
  12.     {  
  13.         this.ProductId = productId;  
  14.    
  15.         this.DoSanityCheckOnArguments();  
  16.     }  
  17.    
  18.     private void DoSanityCheckOnArguments()  
  19.     {  
  20.         if(this.ProductId == Guid.Empty)  
  21.         {  
  22.             throw new ArgumentException("productId""Failed to initialize GetProductCommand. Invalid product Id received.");  
  23.         }  
  24.     }  
  25. }  
  26.    
  27. /// <summary>  
  28. /// Contains results of GetProductCommand execution.  
  29. /// </summary>  
  30. public class GetProductCommandResult : BaseCommandResult  
  31. {  
  32.     public Product ProductDetails { getset; }  
  33. }  
Now let’s add the GetProductCommandHandler. The GetProductCommandHandler will contain the execution logic, which will be executed in a really controlled environment. Inherit the class from BaseCommandHandler with generic argument of type GetProductCommand and GetProductCommandResult. Once you finish writing the following syntax, press ctrl + . in visual studio and you’ll be prompted to implement the abstract class.

BaseCommandHandler
  1. public class GetProductCommandHandler: BaseCommandHandler < GetProductCommand, GetProductCommandResult >  
  2. {  
  3.     protected override GetProductCommandResult ExecuteCore(GetProductCommand command)  
  4.     {  
  5.         throw new NotImplementedException();  
  6.     }  
  7.     protected override GetProductCommandResult GenerateFailureResponse()  
  8.     {  
  9.         throw new NotImplementedException();  
  10.     }  
  11. }  
Add the “Core Logic” to fetch the product here. Build an error response if anything goes wrong. This is how the final class would look like after doing the patching work.
  1. public class GetProductCommandHandler: BaseCommandHandler < GetProductCommand, GetProductCommandResult >  
  2. {  
  3.     private IRepository repository;  
  4.     public GetProductCommandHandler()  
  5.     {  
  6.         repository = new ProductRepository();  
  7.     }  
  8.     protected override GetProductCommandResult ExecuteCore(GetProductCommand command)  
  9.     {  
  10.         if(command == null)  
  11.         {  
  12.             throw new ArgumentNullException("command""GetProductCommand object was received null.");  
  13.         }  
  14.         var product = repository.Fetch(command.ProductId);  
  15.         var productDetails = new GetProductCommandResult  
  16.         {  
  17.             ProductDetails = product  
  18.         };  
  19.         return productDetails;  
  20.     }  
  21.     protected override GetProductCommandResult GenerateFailureResponse()  
  22.     {  
  23.         return new GetProductCommandResult  
  24.         {  
  25.             Error = new ErrorDetails  
  26.             {  
  27.                 // Move it to shared constant file  
  28.                 Code = 200001,  
  29.                     // Load it from string resource file  
  30.                     Message = "There was an error while retreiving product details."  
  31.             }  
  32.         };  
  33.     }  
  34. }  
Now if you want you can also write some unit tests against the Command testing the individual logic of each operation. Instead of testing the whole big old mud ball service façade.

Core logic is now moved from Service contracts to a dedicated command. Now we need find a way to send those operation requests to respective commands. Let’s create a class CommandDispatcher. This class will have only Dispatch method which will actually take the command dispatch it to their respective command handler.
  1. public static class CommandDispatcher  
  2. {  
  3.     /// <summary>  
  4.     /// Keep the cached instance of command handlers.  
  5.     /// </summary>  
  6.     internal static Dictionary < Type, Object > localCache = new Dictionary < Type, object > ();  
  7.     /// <summary>  
  8.     /// Register all the command handler found  
  9.     /// </summary>  
  10.     static CommandDispatcher()  
  11.         {  
  12.             // A DI container can be used here.   
  13.             // This is a composite root for registering all command handlers.   
  14.             var coreAssembly = typeof (ICommandHandler < , > )  
  15.                 .Assembly;  
  16.             var commandTypes = from type in coreAssembly.GetExportedTypes()  
  17.             where type.Name.EndsWith("CommandHandler")  
  18.             select type;  
  19.             // Register the handlers’ instances to local cache  
  20.             commandTypes.ToList()  
  21.                 .ForEach(type => localCache[type] = GetInstance(type));  
  22.         }  
  23.         /// <summary>  
  24.         /// Method to locate and execute the command on their respective command handler.  
  25.         /// </summary>  
  26.     public static TResult Dispatch < THandler, TResult > (BaseCommand command)  
  27.         {  
  28.             var handlerType = typeof (THandler);  
  29.             var handlerInstance = Get < THandler > ();  
  30.             var methodInfo = handlerType.GetMethod("Execute");  
  31.             return(TResult) methodInfo.Invoke(handlerInstance, new []  
  32.             {  
  33.                 command  
  34.             });  
  35.         }  
  36.         /// <summary>  
  37.         /// Get the registered command handlers.  
  38.         /// </summary>  
  39.     internal static THandler Get < THandler > ()  
  40.         {  
  41.             object cachedInstance = null;  
  42.             if(!localCache.TryGetValue(typeof (THandler), out cachedInstance))  
  43.             {  
  44.                 throw new InvalidOperationException("Command Handler for the respective command is not registered.");  
  45.             }  
  46.             return(THandler) cachedInstance;  
  47.         }  
  48.         /// <summary>  
  49.         /// For testing purpose only.  
  50.         /// </summary>  
  51.     internal static void ResetCache()  
  52.     {  
  53.         localCache.Clear();  
  54.     }  
  55.     private static object GetInstance(Type type)  
  56.     {  
  57.         return Activator.CreateInstance(type);  
  58.     }  
  59. }  
This CommandDispatcher is doing the following work:
  1. Register instances of all the command handlers (this work can be replaced by using DI container).

  2. Locate and execute the command on its handler via Dispatch method.

To test the Dispatcher, I’ve created a few tests around (and actually found couple of bugs to fix before using the code in this article). Refer to the sample solution here on github.

We have our Dispatcher in hand. Let’s patch it to the Service contract operations and finish the bonding of Dispatcher/New façade to Service contracts.

  1. public class ProductService: IProductService  
  2. {  
  3.     public Product Get(Guid productId)  
  4.     {  
  5.         var commandArgs = new GetProductCommand(productId);  
  6.         GetProductCommandResult result = CommandDispatcher.Dispatch < GetProductCommandHandler, GetProductCommandResult > (commandArgs);  
  7.         // Raise the fault exception  
  8.         if(result.Error != null)  
  9.         {  
  10.             throw new System.ServiceModel.FaultException < Exception > (new Exception(result.Error.Message));  
  11.         }  
  12.         return new Product  
  13.         {  
  14.             // map the GetProductCommandResult.Product properties to proerties of contracts.   
  15.         };  
  16.     }  
  17. }  
That’s it. Pretty clean huh! Question yourself what impact would move Get() method from this contract to another contract or completely removing the method from service contract. Yes, remove it right away the Core Logic is safe and sound and can easily be used in another service. Also we have no dependencies of the system on contracts anymore. Core service logic unit is abstracted via CommandDispatcher and Commands. Such implementation promotes more cohesiveness and less coupling in the system.

I’m sure some readers might have observed that we have introduced a new design patterns as well while refactoring. Now Service contract is actually behaving as Adapter class for its consumer and the core service logic unit i.e. BusinessLogic. That’s how, IMO, the service contracts should behave in the system.

There are Pros and Cons (not much) of using this separation so before we wrap up let’s take a look at them.

Pros:
  1. Separated business unit from contracts.
  2. Minimized the contract changes impact on core service logic.
  3. More controlled execution of business logic via commands.
  4. Each command is representing a service operation which is placed in a dedicated class means more scope to do with operations.
  5. More opportunities to add unit tests at its core logic unit i.e. Commands.
  6. Old service façade are now Adapters.

Cons:

  1. Bolerplate Code (This complain usually heard from developers. But this boiler plating is worth for long run, and of course it can also be optimized by techniques like Aspects Oriented Programming).

  2. Additional mapping of Contacts and Business Entities. (This can be handled by using an awesome utility Automapper). Thanks to Jimi and community developers doing this great piece of work.

For further reading on best SOA practices and patterns I would suggest to read “SOA Design Patterns” by Thomas Erl.

Solution used in the blog post is hosted on Github here.