Dexter  Goodwin

Dexter Goodwin

1624559580

How to Avoid Callback Hell in Java

Don’t bring your JavaScript code smells to Java

JavaScript coders recognize the deeply nested callbacks that were the original way of dealing with asynchronous code and have given it a name. Since JavaScript only has a single thread, blocking is a no-no, so any code that has I/O needed to have a function that would be called when the request was finished. So you would have code like this:

messageQueue.read("incoming", (merr, mdata) {
  if(merr) return merr 
  webClient.post("/endpoint", mdata, (werr, wdata) {
    if(werr) return werr 
    val query = queryBuilder(wdata)
    database.lookup(query, (derr, ddata) {
      if(derr) return derr 
      messageQueue.write("outgoing", ddata, (oerr, odata) {
        if(oerr) return oeff
        console.log("message written")
      })
    })
  })
})

This is the most straightforward way of writing code when the blocking methods all take a function as a parameter, but reading it can give you a headache. If the code gets too wide, it scrolls off the side of the screen. Sure, you could use that as an excuse to buy a wider monitor or you could just get used to horizontal scrolling. But I’d rather have short lines that fit on the screen.

#android #java #javascript

How to Avoid Callback Hell in Java