Avoiding Nested Callback Complexities In Vert.x And Java 8

If you have experience using callbacks in various applications and languages (Node, Swing, Vert.x, etc...), you are probably familiar with what some people refer to as Callback Hell.

Generally, you have some sort of anonymous function within an anonymous function and chaining deeply until you see something like: One way that I have used to avoid this difficult to read code is to use method references in Java 8. This has the added benefit of making your methods easier to test without having to expend Herculean effort in order to handle asynchronous processing.

Let's look at a real-world example of some Vert.x code:

As you can see, this code contains many levels of nested callbacks and checks for the results. This is difficult to read and extremely difficult to test. Let's look at an alternative which makes use of method references to make this easier to read and easier to test.


This refactored example shows ow we can created individual methods which can be used in place of the in-line lambdas. This has several benefits:

  • The methods can have descriptive names explaining what they do
  • The methods can have JavaDoc comments to explain them in more detail
  • The methods have all of their parameters passed in at call time, so they can be easily tested with mock or stubbed objects.

If you follow this methodology, your async code can become more testable, more readable, and more maintainable as you go.

Comments

buy essay cheap said…
This comment has been removed by a blog administrator.

Popular Posts