This blog post is about writing better code. In particular, we focus on methods commonly espoused by functional programmers. A lot of the subsequent ideas presented are inspired by the works of Eric Normand and Robert Cecil Martin, and by my own share of recent trials and tribulations involved with refactoring legacy code.

Why write better code?

Primarily, we write better code to reduce technical debt. Technical debt is the implied cost of additional rework caused by coding an easy solution1. It’s essentially a trade-off. You could build an easy and quick ad hoc solution and spend more time debugging/modifying the code in the future or spend more time on a robust solution and spend less time debugging/modifying.

We refactor or rewrite existing code when technical debt is high enough. Such a decision is in no way trivial, though an oversimplification (as shown below) might be helpful in thinking through it.

\[ T_d = Estimated\:technical\:debt\:(hrs)\\ T_r = Estimated\:time\:to\:refactor\:(hrs)\\ T_{diff} = T_d - T_r\\ \mathbf {1} _{refactor}(T_{diff}):= \begin{cases}1~&{\text{ if }}~T_{diff} > 0,\\0~&{\text{ if }}~T_{diff} \le 0\end{cases} \]

A case study: Introducing NoviParlor

We shall now look at a simple case study to illustrate some of the best practices of functional programmers. Introducing NoviParlor: Durham’s newest ice cream shop. You are tasked with writing code that calculates the final price of placed orders. The final price takes into account:

  1. Number of scoops
  2. Ice cream flavors: Vanilla, Chocolate, Gooey Cake and Haskell. All flavors have different prices associated with them.
  3. Toppings: Dry, wet or gold.
  4. Discounts: NoviSci employees get a 20% discount. Statisticians at NoviSci get a 30% discount (don’t ask me why). And orders >$20 get a 10% discount.