Embrace Mutation with Object Orientation

I know that a lot of people watch this channel to learn about functional programming in Kotlin.

Some of those that already know about functional programming in Kotlin have, how shall I put it, raised concerns about the JSON parser that I am writing because, well it really isn’t very functional at all. It works by mutating its internal data structures as it processes characters, meaning that it is composed of impure functions. In fact, it is an old-school object oriented design, with classes encapsulating state.

I didn’t set out to write code one way or the other – this has been an honest experiment in writing a parser following the rules of TDD – and it’s quite a surprise to me how deeply unfashionable the result has turned out to be. But I’m actually quite pleased with what we have, and, as you’ll see in this episode, end up doubling down on mutability in order to process escape sequences inside JSON strings.

This is episode 7 in a series on writing a simple JSON parser in Kotlin. You can see the playlist here – https://www.youtube.com/playlist?list=PL1ssMPpyqocicj5gxqpPDA1iZu9OX3YBT and the code on GitHub https://github.com/dmcg/json

In this episode

  • 00:01:08 Review JSON escape sequences
  • 00:01:53 Look at our current escape plan
  • 00:02:24 Refactor escaped quote to a state machine
  • 00:03:57 Using an inner class to mutate the outer class
  • 00:04:54 Introduce Escaped state
  • 00:08:45 Now we can implement all the single character escapes
  • 00:12:41 Now Unicode escapes
  • 00:14:56 Fake it until we make it
  • 00:16:35 AI assistant to the rescue…
  • 00:16:52 …after we ask the right question
  • 00:18:02 Add a test for an invalid escape
  • 00:18:54 Fix the error message
  • 00:19:45 Refactor to make a method fit on the screen
  • 00:21:27 Add tests for illegal Unicode escapes
  • 00:24:16 IntelliJ bug
  • 00:26:02 Review StringState before checkin
  • 00:26:19 Oh, another error message to improve
  • 00:27:50 Checkin
  • 00:28:06 Thinking about mutability
  • 00:30:05 Next week, we check correctness

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.

submitted by /u/dmcg
[link] [comments]