Refactoring to Higher-Order Functions - Creating a declarative API for http4k

Опубликовано: 02 Май 2026
на канале: Pairing with Duncan
872
42

Regular viewers will know that I’m a big fan of http4k (https://www.http4k.org) for all my HyperText Transfer Protocol needs. It’s fast, expressive, and versatile.

Compared to frameworks such as Spring though, it leaves higher-level abstractions to us. A Spring controller allows us to use annotations to map a method to an HTTP route and verb, extract parameters and convert them to domain types, and map results back into an HTTP response. We can do all those things in http4k, but the actual wiring is not declarative; we have to work out where to do it.

The code we are going to refactor today has lots of HTTP handlers, and so we have got to the stage where we can look at the ways that it is using http4k, and try to express in software the patterns we see. Can we find a way to separate the concerns of HTTP mapping from our application logic? Or put another way, can we reproduce Spring’s automagic, but in a way that we own and understand?

In this episode

00:01:17 Introducing the FakeFrobulator
00:02:00 It has HTTP handlers bound to routes
00:03:04 We have tests that we mainly trust
00:03:47 We see that our handler mixes business logic with HTTP mapping
00:04:38 Extract a function for the business logic
00:05:02 Separate configuration from per-request and generalise all the things
00:06:39 Extract the per-request code into an HttpHandler lambda
00:07:43 Extract the code that build the HttpHandler into a method
00:08:02 Generalise all the types
00:09:56 This function is handlerFor
00:10:19 Now we can inline lots of things
00:11:48 Review that change
00:12:40 Checkin
00:12:48 Is handlerFor applicable in another case?
00:13:13 Refactor to use it
00:15:56 Commit
00:16:03 What about a case that can go wrong?
00:17:17 Again separate mapping from logic
00:22:00 A nice refactoring to using a result type
00:26:20 Repeat the refactoring combo
00:29:20 Tidy up
00:30:51 Review
00:31:37 Check in
00:31:44 Check that another case can be refactored in the same form
00:33:02 Next time

I'm hugely grateful to my clients, https://www.home.cc , for permission to show parts of their codebase, for which they hold the copyright, and to Orion Williams for the music http://toolofgod.com/my-music/royalty...

There is a playlist of http4k content    • http4k  

If you like this, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It's about far more than just the syntax differences between the languages - it shows how to upgrade your thinking to a more functional style.