How does Haskell make your life easier?

November 30, 2019
« Previous post   Next post »

Why use Haskell?

Do you hate:

  • Losing hours or weeks debugging obscure bugs deep in your stack because it's hard to test or observe what's going on?
    • Worse, having to debug in production because something didn't get caught during release?
  • Getting woken up at 3AM by random alerts because your application keeps crashing/throwing runtime errors for your users?
  • Being afraid of changing the core parts of your codebase, even if they're buggy and poorly designed, because it would be too difficult to make changes without breaking everything?
  • Coming back to an old codebase in 6 months or a year and having no idea how anything works and not knowing how to make working changes?

What if you could:

  • Release to production fearlessly, with total peace of mind that nothing will break?
  • Never have a crash or runtime error in prod ever again?
  • Refactor one of your core files to expose a better API...
    • ...and change your entire codebase to use the new interface
    • ...without introducing any regressions
    • a day?1
  • Change old code with complete confidence that it will still work?

Haskell can do that.

I know, I know, it sounds impossibly far-fetched. Just trust me for a second that these are all benefits that Haskell developers take advantage of each and every day. (Okay, maybe not refactor the whole codebase every day. That would be a little excessive.)

You don't have to take just my word for it, either.

We took the typechecker for [a compiler] and were about half way through writing it in Haskell. [..] We had to stop and work on something else for 6 months mid-authorship. We came back, dusted it off for a week, updating dependencies. Slotted in and got to work...and it worked perfectly the first time. Then we found we could shed 30% of it. Did so, and it still worked perfectly.

I can make sweeping changes to my API, get all the bugs caught by the type system, and still have minimal code impact.

That freedom to refactor is probably my greatest love for Haskell.

"Meditations on learning Haskell"

You might come to Haskell from a dynamically typed background like JavaScript, Python, or Ruby where you learned to avoid refactoring large code bases due to the lack of static types. This aversion to refactoring promotes a culture of "big-design-up-front" where you try to get your project as close to correct on the first try so that you don't have to refactor your code later.

Refactoring is cheap in Haskell so you don't need to get things right the first time.

— Gabriella Gonzalez, "Advice for Haskell beginners"

A crucial aspect of difficult problem solving is that you’re frequently wrong. You pursue an idea for a long time, only to discover that you had something backwards in an important way, and need to make some pervasive changes throughout your work. Note that the maintenance programmer’s “surgical modification” style is a horrible idea here; the last thing you want, when you’re already working at the limits of your ability, is to wade through code whose structure arose out of your past major mistakes. Rather, what you need is a way to make deep structural changes to your code, and still end up with a fair amount of confidence that the result is at least reasonable, that you haven’t forgotten something big.

— Chris Smith, "Haskell's Niche: Hard Problems"

I've talked a little bit about the nitty-gritty of how to write code to accomplish these things before, but let's instead take a 10,000-foot overview of how Haskell's design makes this level of bug-freeness and maintainability not just possible, but easy. These benefits aren't cherry-picked cases; it's not a case of "if you expend a lot of effort, encode very strict engineering discipline, and ruthlessly enforce code hygiene, maybe you'll end up having these benefits." No, they're a core part of the experience of using Haskell to write real programs.

The secret of Haskell: Extreme maintainability through types

Because Haskell's rich type system lets your developers model the domain precisely and in a complete way, it's easier for the same developers to return months or a year from now, or new developers to arrive, and gain a good grasp of what's happening in the system.

— Chris Done, "Software project maintenance is where Haskell shines"

If you've spent time reading about Haskell, you'll likely have noticed that a lot of the literature is about types. That's not a fake-out: a large amount of the benefit of Haskell derives solely from its unusually strict type system.

We're only going to mention the specific attributes of the type system in passing, since they've been talked about to death elsewhere. In brief: no nulls; errors and the possibility of returning nothing are represented explicitly. Algebraic data types model alternatives easily. Well-implemented generics (polymorphism) and typeclasses means more reusable code. Type inference means that syntactic noise from having to specify types is minimal. Side effecting code is clearly separated from pure code at the type level.

A key consequence of all this is that it's possible to write functions that need no validation done on their inputs.

What does that mean? In other languages, if you pass an empty array to a function that only works on nonempty structures, it's a toss up as to what will happen. Maybe it'll return some junk data that you have to check for. Maybe it'll silently give you a wrong answer. Maybe it will crash your program. All of these are annoying, but more importantly, they degrade the quality of your program. It's up to you to manually make sure they don't happen, and if you make a mistake (as is human), your program starts misbehaving, likely in ways that cause you to lose time, customers, money, and/or sanity.

Try the same thing in Haskell, and your compiler will catch the potential error for you. You can write a function that is impossible to call with, say, an empty array; your code will simply refuse to compile. Nulls are the most talked about example when it comes to the benefits of strongly-typed functional programming, and indeed being able to use your function parameters immediately without having to do any null checking at all is very nice. But this idea extends to basically any piece of data. You can write functions that only take:

  • nonempty lists or arrays
  • nonempty strings that also aren't all whitespace
  • nonnegative integers
  • only users that have paid
  • only validated emails
  • only sanitized strings
  • ...and so on

and have your compiler check that you got it all right.

Your compiler checks for you whether all your function calls will complete successfully. And since a program is basically a big tree of function calls, if every call will complete successfully, your whole program will complete successfully.2 Haskell is much more precise about exactly what inputs your code needs, including permissions for things like DB or filesystem access.

Consequence 1: Bugs become harder to create

While you still have to get your business logic right, the type system catches a lot of stupid errors for you.

Put another way, the only thing you have to worry about is getting the business logic right; the "plumbing" of making sure that you're not accidentally passing wrong data or failing to handle an edge case is handled by the compiler for you. Coincidentally, these kinds of issues are exactly the most likely to trip you up when doing refactors and maintenance, since you're not changing what the program is doing, just how it's structured. While your compiler doesn't guarantee that your code will give you the right answer, it does guarantee that you'll get an answer, which is in itself eliminating a whole class of bugs. And with less headspace used handling the stupid errors, you should be better equipped to handle the hard bits, right?

Consequence 2: Maintenance requires less brainpower

If the compiler is making sure that all your function usage is safe, that holds just as true when you add new code, and when you're refactoring old code.

So you have the ability to:

  • Change core types
  • Delete huge swaths of unnecessary code
  • Add new features
  • Refactor the codebase to completely change the fundamental design

all while having complete confidence that your code will still work afterwards. Things that would require deep understanding of the what the code is doing in other languages instead become mechanical exercises in Haskell because the type checker will catch your mistakes while making changes.

In other languages, maintenance is a process of figuring out which code to change to implement your feature (easy), and then figuring out which other code needs to change as a consequence of that (hard). In Haskell, the compiler handles the second part for you.

Consequence 3: Taking shortcuts becomes harder

Developers using [a language that incentivizes taking shortcuts] might compensate by creating a culture that shames worst practices and glorifies best practices in order to realign incentives, but this does not scale well to large software projects and organizations. You can certainly discipline yourself. You can even police your immediate team to ensure that they program responsibly. But what about other teams within your company? What about third-party libraries that you depend on? You can't police an entire language ecosystem to do the right thing.

— Gabriella Gonzalez, "Worst practices should be hard"

An objection you might have is that Haskell being easier to maintain is only true if everyone touching the code is on the same page and expends the same amount of effort keeping things kosher. You've seen the same thing happen to countless projects. Everyone starts off trying to write good code. Deadlines need to be met, targets need to be hit. People start cutting corners to get things done. You poke a hole in an interface to access some internal functionality. You pull a private attribute out because you really need to use it now. The codebase slowly, surely, deteriorates.

Fundamentally, this happens because most modern languages are permissive; if you want to use global state, or send an API request deep within some business logic to fetch something you don't have, there's nothing stopping you. It's a one line change to do it the "bad" way, and potentially a lot of refactoring to do it the "good" way. If the effort/reward curve is skewed that way, is it a surprise that people resort to dirty hacks?

Haskell takes the opposite approach: by default, it's extremely restrictive. If you want to access something, or make a network request, or access the database, you have to explicitly ask for it. Because of this, breaking abstractions open and using their stinking guts directly is much less appealing; you might have to make changes in potentially your entire codebase to do so. Doing things the "good" way becomes less effort than doing things the "bad" way. If your core types are set up well, any code using them will naturally have to adhere to the constraints that said types impose. That only has to be done once, potentially only by one developer! You get maintainability throughout the lifetime of your code, simply because the easiest thing to do is to do it right.

What's the catch?

Getting all of these maintainability benefits probably still sounds too good to be true.

  • The library situation is adequate, but only just. While you'll find good libraries for a lot of your backend needs, other areas are oddly anemic. For instance, you might end up having to roll your own authentication stack.
    • A big category here is access to third-party APIs. Since Haskell isn't a first-class citizen when it comes to SaaS services providing library bindings, expect a Haskell binding to not exist for any third party you use, and budget in time to write a client, even just a thin binding over HTTP requests.
  • Documentation sucks. Even for popular libraries, expect less and lower-quality documentation than you'd get for, say, any popular Python library picked using rand(). Sometimes you'll get lucky and a library will have both solid reference documentation and lots of examples to help you get started. Sometimes you'll get sparse reference docs that are accurate in the small but don't help you get the big picture at all. Sometimes you get the lens library.
  • Tooling is just okay. If you're okay with developing on the command line, the experience isn't that bad. But expect to lose time paging back and forth between your editor and documentation. Other things that help cut down on the development loop, like immediate highlighting of type errors and autocompletion based on type, are rather patchy and require finicky setup.
  • Testing is great, but you'll need to budget time for it. Through a combination of Haskell code both being fundamentally easier to test, having best-in-class tools and libraries for writing tests, and Haskell having a relatively weak story for runtime debugging, the main way of checking your code before you deploy it is... by writing tests. As a biased party, I think this is definitely a good thing overall, since tests are much better for ensuring quality in the long run than stepping through breakpoints. But it does mean you'll incur some overhead writing them.

In summary, the biggest downside to writing Haskell is that you'll have to spend more upfront time, whether that's on the level of a project or an individual feature. In return, you'll spend a lot less time on the tail end of already "completed" tasks hunting down bugs, constantly patching unreliable code, and chasing alerts to the end of time. Pick Haskell as an investment into your time and sanity, whether that's 3 months, 6 months, or years down the line. Pick Haskell for the long term.

Found this useful? Still have questions? Talk to me!

You may also like

« Previous post   Next post »

Before you close that tab...


↥1 Some of the examples in this post draw from other languages in the strongly-typed family. In practice, a lot of the benefits explored here apply equally well to these similar languages, so maintainability benefits enjoyed by, say, F#, OCaml, Elm, PureScript, Rust, and Scala, among others, are true of Haskell as well.

↥2 Or keep running forever successfully, depending on what you’re developing.