Reading Time: 5 minutes

Would you like chicken or pasta? Chocolate or vanilla? Coffee or tea? White wine or red? Component or transformer? If you have a piece of custom code, should you implement it as a custom transformer or as a custom component?

Technically, you can do either. But under what circumstances is it better to use a transformer versus a component?

latest report
Learn why we are the Leaders in API management and

Let's take a look at the Mule's Hello World example.  At the beginning of the code, there's a composite message source and each endpoint in it has an attribute called ‘transformer-refs'.  These transformers convert input to an instance of NameString class. Note that they change the data representation format (from String or HttpRequest to NameString object) but not the data itself; that is, they don't remove or add any information.

Further down the flow, invokes the Greeter component which adds the greeting part to the NameString object. For example, if the input NameString payload contains the name “Muley”, the returned object will contain the greeting string in addition to the name. Essentially, the component has added the new information.

Ergo, where the custom code converts data from one representation format to another, implement it as a transformer; where it creates new data, implement it as a component.

But, of course, there's just a little more to it. Let's take a closer look at the flow: as you can see, all transformers are defined globally. It makes sense to use globally defined transformers when you want to them in multiple places in your Mule flows. So if you want to convert data from one format to another, and you plan on reusing the same transformer many times in your Mule flows, implement your custom code as a transformer.

You can reference the transformer in your flow in a couple of ways:

  • in the endpoint transformer-refs attribute  (This allows you to create transformation chains, such as transformer-refs=”HttpRequestToString StringToNameString”)
  • in the flow using the <transformer ref=”…”/> element.

Note, however, in order to implement transformers your code has to extend one of two abstract Mule classes – AbstractTransformer or AbstractMessageTransformer. Further, your transformers can only have one entry point. With these added configuration details and constraints, implementing custom code as a transformer might seem a bit more work, so Mule 3.3 introduce a new feature called a Converter. A Converter enables Mule to auto-discover the transformer code and any implicit transformation chains.

Components, on the other hand, can be implemented as simple POJOs and can have multiple entry points. That they can be so simply customized is a stroke in their favor.

So, what's it going to be?  Chicken or pasta? Convert data or create new?