Recently I was caught up in the discussion about early bound entities and late bound entities. One of the argument of the “late bound supporters” was the fact, that using late-bound allows reusing the same plugin for multiple entities (so for example create a plugin that runs for all activities or a common plugin for leads/opportunities/accounts). This argument is not valid, I will show you how to write a clean code, that uses modern approach for coding and is perfectly testable.
Let’s start with the late bound version of the plugin to give you an idea what are we trying to achieve here:
The plugin simply adds values of “new_netamount” and “new_margin” fields on the entity and sets field “new_totalsum” to a resulting value. Of course this can be simply achieved by using calculated field, but I just want to show the basic idea here, real world scenario is usually much more complicated.
Now it’s much better, but there is a significant problem with this code. We assumed that our plugin runs on Account entity. What if we will register it on Contact entity? Well, it will simply crash when we will try to convert our target!
So the basic approach would be to create a switch statement and simply check the entity type:
Ok so now we can register the plugin on multiple entities, but our code looks even worse than the first version, because we have a lot of code that is copy-pasted. Imagine that the operation would be much more complex and would change frequently in time – we would have to change all the switch statements every time.
To overcome this problem we will take advantage of the fact that all early-bound classes are partial, so they can implement any interface we want. Let’s create such interface and some helper partial classes:
It would be great if we could use this like that:
But unfortunately, our “Target” is an entity and we have to somehow convert it to an early bound. I developed a simple utility class that is capable of that:
Simple explanation of the code – during first execution of the plugin, all the early-bound types are cached in a dictionary, that can be later fast accessed from the code (in this case it’s InterfaceMocker). It simply instantiates the early-bound and copies all attributes inside. There is also an extension method that simplifies the usage for Entity. Now our plugin can simply look like that:
And that’s it! This code looks much better then late bound version, provides type-checking for entity attributes and also is very nice when we implement unit tests, as we have an interface to test, not a full early-bound. If our logic is more complex we can create some additional classes that will be dependent upon IEntityWithTotalSum interface, not Account or Opportunity entity.