Lesson 23. Business rules as code

 

In this last lesson of the unit, you’ll see how to use F# language features such as records, options, and discriminated unions to write code that can enforce business rules within code. This lesson covers the following:

  • Conventional ways to validate business rules
  • Exploring domain modeling in F# more closely
  • Exploring single-case discriminated unions
  • Encoding business rules through types
  • Exception handling

Our code always has some form of business rules within it. Generally, we validate that our code is correct either by running the application and manually seeing whether it does the right thing, or by writing some form of automated test suite that sits alongside our code. This test suite often is as large as the “real” code base itself, and runs tests in code that check the results of the application.

There are, of course, limits to what these tests should and shouldn’t do. Because C# is a statically typed language, there are certain tests that we don’t need to perform, because the compiler gives us certain guarantees. For example

  • We don’t ever need to check that the Name property on a Person class, which is a string, contains an integer. The type system provides that for free.
  • We don’t ever need to check that an int is null.

But here are some things that we might want to write automated tests for:

23.1. Specific types in F#

23.2. Encoding business rules with marker types

23.3. Results vs. exceptions

Summary