Type Driven Development in Kotlin – Extending the Bowling Kata

We’re taking another little break from Gilded Rose this week to look at software design, and in particular domain modelling – how we represent aspects of the real world in our software.

The domain that I’ve chosen is 10-pin bowling. There is a bowling kata; but that is only concerned with the scoring of a game. I’m more interested in the game state – the progression of a game, whose turn it is, when it ends etc.

As an experiment, instead of test-driven design, I’m going to see how far we can get with type-driven design. We’re going to start by identifying the types of things that we see in the domain – players, frames, pins and so on, and see how we can model these in Kotlin types.

Then we will look at the relationships between those types, again expressing them in Kotlin code.

Finally, we look at the operations that those types support. Types can guide us here too, suggesting implementations based on how we can derive an output type from the input types.

By the end we have a reasonably complete Kotlin model of the domain, some method definitions, and some TODOs where I really don’t feel comfortable guessing at an implementation without writing some tests.

In this episode

  • 00:01:19 Looking for the types
  • 00:02:47 Write empty classes for types
  • 00:03:14 Use information from the domain to constrain some types
  • 00:04:45 Find has-a relationships between types
  • 00:07:39 So far we have described the data
  • 00:08:21 Now look for operations on the types
  • 00:08:38 Introduce types to prevent invalid operations
  • 00:10:21 Sketch an implementation of roll based on the types
  • 00:13:02 TODO() anything that looks complicated
  • 00:13:59 Introduce types to simplify implementation
  • 00:14:14 IntelliJ inline bug
  • 00:15:01 Introduce more types when we see different states
  • 00:16:00 Review our previous usage when we add subtypes
  • 00:16:25 Implement operations based on narrowing types
  • 00:17:20 Go down a level and repeat the process
  • 00:18:49 Finally look at types of frames
  • 00:20:35 Its OK to change our type relationships as we learn
  • 00:23:43 Nullability can be removed down a type hierarchy
  • 00:24:05 Tidy before we go on
  • 00:25:47 Asymmetry can give type clues
  • 00:27:21 We are missing some logic – they are TODO()s
  • 00:27:54 A diagram!
  • 00:28:57 Review

You can see the code on GitHub https://github.com/dmcg/bowling-for-youtube

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]