Plugin development: don’t use Context.Depth to prevent recursions!

By | June 18, 2018

It’s been said a number of times in different blogs that context.Depth may have side effects, but I am starting to think we should actually ban the practice of using context.Depth all together.

It’s almost impossible to predict plugin execution paths as long as your solution gains any level of complexity, but, even in a relatively simple scenario below, you may quickly start noticing how your data is becoming inconsistent over time:

image

That validation plugin at the bottom will run when Entity 3 is being updated through the UI. And it will not run when Entity 3 is being updated from one of the other plugins (each of those may run in response to some other events).

So, basically, you may either have to repeat validation logic in each and every plugin affecting Entity 3, or you may have to come up with some other way to avoid recursions. The easiest solution would be to carefully control which attributes are updated every time and which attributes are configured to trigger the plugin.

Problem is, if you don’t do that, fixing those issues in the existing solution can quickly turn into a nightmare. When developing new functionality you will be assuming that validations are working, so you might not even bother to test some of them until it’s already too late and your data has become inconsistent. At which point you’ll have to fix it somehow, explain the consequence to the users, etc.

So take your time to craft the validation criteria carefully, don’t use Depth, and you should be able to save yourself from those troubles.

3 thoughts on “Plugin development: don’t use Context.Depth to prevent recursions!

  1. Vangelis

    Thanks for sharing this. Without disagreeing in the points you make, especially about controlling the attributes updates, I would like to share my experience that so far serves me well. I am following a standard technique in my plug-ins architecture that the plug-in is allowed to run up to a specific depth. There is a validation piece of code that throws exception when the plug-in goes over the allowed depth. The same is also part of the automated unit tests to ensure a conscious decision of the maximum allowed depth. During system and integration testing the exception will be raised and avoid unwanted issues in the live environment.

    Reply
    1. Alex Shlega Post author

      Hi Vangelis, this makes sense – it does looks like a good practice. More often than not(almost always, actually) I will see examples where no exception is thrown. Instead, it’s, usually, if (context.Depth > …) return;, and that’s what’s causing the problem…

      Reply
      1. Vangelis

        Unfortunately, I have to agree that this happens very often!

        Reply

Leave a Reply

Your email address will not be published. Required fields are marked *