Solving common problems functionally

 

Chapter 14 from The Joy of Kotlin by Pierre-Yves Saumont

This chapter covers

  • Using assertions
  • Automatic retries for failing functions or effect applications
  • Reading property files
  • Adapting imperative libraries
  • Converting imperative programs
  • Repeating effects

You now have many tools that can make your life as a programmer easier by using safe programming techniques coming from the world of functional programming. But knowing the tools isn’t enough. To become efficient using functional techniques, you must make them second nature. You need to think functionally. Just as object-oriented (OO) programmers think in patterns, functional programmers do the same with functions.

When OO programmers have a problem to solve, they look for design patterns they can recognize and attempt to reduce the problem to a composition of patterns. Once they’ve done that, they need to implement the patterns and compose them.

Functional programmers do the same with functions with one difference: when they find that a function could be used to solve a problem, they don’t have to reimplement it. They can reuse it, because functions, unlike design patterns, are reusable code.

14.1 Assertions and data validation

14.2 Retries for functions and effects

14.3 Reading properties from a file

14.3.1 Loading the property file

14.3.2 Reading properties as strings

14.3.3 Producing better error messages

14.3.4 Reading properties as lists

14.3.5 Reading enum values

14.3.6 Reading properties of arbitrary types

14.4 Converting an imperative program: The XML reader

14.4.1 Step 1: The imperative solution

14.4.2 Step 2: Making an imperative program more functional

14.4.3 Step 3: Making the program even more functional

14.4.4 Step 4: Fixing the argument type problem

14.4.5 Step 5: Making the element-processing function a parameter

14.4.6 Step 6: Handling errors on element names

14.4.7 Step 7: Additional improvements to the formerly imperative code

14.5. Summary