I’m your classic OOP developer. However since I discovered purely functional programming languages I’ve been ever intrigued to the why since OOP seemed to solve most business cases in a reasonable manner.
I’ve now come to the point in my software development experience where I’m seeking more concise and expressive languages. I usually write my software in C# but for my latest project I decided to take the leap and build a business service using F#. In doing so I’m finding it very hard to understand how decoupling is done with a purely functional approach.
The case is this. I have a data-source, which is WooCommerce, but I don’t want to tie my function definitions to that specific data source.
In C# it is apparent to me that I want a service that looks something like this
public record Category(string Name);
public interface ICategoryService
{
Task<IEnumerable<Category>> GetAllAsync();
}
// With a definition for the service that specifies WooCommerce
public class WcCategoryService : ICategoryService
{
private readonly WCRestEndpoint wcRest;
// WooCommerce specific dependencies
public WcCategoryService(WCRestEndpoint wcRest)
{
this.wcRest = wcRest;
}
public Task<IEnumerable<Category>> GetAllAsync()
{
// Call woocommerce REST and map the category to our domain category
}
}
Now in the future, if and when I decide we need a new store for providing categories I can define a new implementation for that specific service, replace the injected type and not mess up the dependents because of this change.
Trying to understand how the functional dependency approach is solved I was met with this case (reading "Domain Modeling made functional") where the type signature directly define the dependencies, so the above C# equivalent would turn into a highly coupled definition
type Category = { Name: string }
type GetCategories =
WCRestEndpoint
-> Category list
Suddenly if I am to change the source of categories I would have to either change the functional signature or provide a new definition to be used which would ripple through the application and thereby not be very robust.
What I’m curious about is whether I’m misunderstanding something fundamental.
With my OOP brain all I can think of doing is something like this
type Category = { Name: string }
// No longer directly dependent on WCRestEndpoint
type GetCategories = unit -> Category list
// But the definition would require scoped inclusion of the dependency
// Also how does the configuration get passed in without having the core library be dependent on the Environment or a config in the assembly?
let rest = WCRestEndpoint(/* Config... */)
type getCategories: GetCategories =
fun () ->
let wcCategories = rest.GetCategories()
// Convert the result into a Category type
I’ve looked around and I haven’t found any explanation as to how change is handled with a purely functional approach, which is what led me to believe there is something fundamental I’ve misunderstood.
How do you expose a functional API without tying the function type signatures up in implementation specific types? Am I thinking about this wrong?
6
Answers
I don’t think there is a single right answer to this, but here is a couple of points to consider.
First, I think real-world functional code often has a "sandwich structure" with some input handling, followed by purely functional transformation and some output handling. The I/O parts in F# often involve interfacing with imperative and OO .NET libraries. So, the key lesson is to keep the I/O to the outside and keep the core functional handling separate from that. In other words, it makes perfect sense to use some imperative OO code on the outside for input handling.
Second, I think the idea of decoupling is something that is more valuable in OO code where you expect to have complex interfaces with intertwined logic. In functional code, this is (I think) much less of a concern. In other words, I think it is perfectly reasonable not to worry about this for I/O, because it is only the outer side of the "sandwich structure". If you need to change it, you can just change it without touching the core functional transformation logic (which you can test independently of I/O).
Third, on the practical side, it is perfectly reasonable to use interfaces in F#. If you really wanted to do the decoupling, you could just define an interface:
And then you can implement the interface using object expressions:
Then, I would have a main function that transforms the
seq<Category>
into whatever result you want and this would not need to takeCategoryService
as argument. However, in your main bit of code, you would take this as argument (or initialize it somewhere when the program starts), use the service to fetch the data and call your main transformation logic.I struggled with this question for years before I realised that I was looking at it the wrong way. Coming from object-oriented development and Dependency Injection, I kept looking for a functional alternative to Dependency Injection. I finally realised that Dependency Injection makes everything impure, which means that you can’t use that approach (not even partial application) if you want to apply a functional architecture.
The red herring is to focus on the dependencies. Instead, focus on writing pure function. You can still use the Dependency Inversion Principle, but instead of focusing on actions and interactions, focus on data. If a function requires some data, pass it as an argument. If a function has to make a decision, return it as a data structure.
You don’t provide any examples of where you’d want to use a list of
Category
values, but a function that depends on such data would have a type like this:Such a function is completely decoupled from the source of the categories. It only depends on the
Category
type itself, which is part of the Domain Model.Ultimately, you’ll need to get the categories from somewhere, but this work you push to the boundary of the system, e.g.
Main
:Thus, if you change your mind about how to get the categories, you only have to change one line of code. This kind of architecture is akin to a sandwich, with impure actions surrounding the pure heart of the application. It’s also known as functional core, imperative shell.
If all you want is to not use objects, it’s a fairly mechanical rewrite.
A single-method interface is just a named function signature, so this:
becomes:
Your composition root becomes a matter of partially applying functions with the concrete implementations of these function arguments.
That said, there is nothing wrong with using objects as such; F# mostly rejects mutability and inheritance, but embraces interfaces, dot notation, etc.
There’s a great slide on OO in F# from a talk Don Syme gave:
You need an asynchronously computed list of categories. There’s already a type for that:
Async<seq<Category>>
. Maybe this was created by a function using aWCRestEndpoint
. Maybe this was created with some constant dummy values in a unit test. Maybe this was created for a unit test and always raises an error. The consuming code doesn’t care. It just cares that there is a way to get the categories.This type is much more reusable than an application-specific
ICategoryService
type. For example, maybe you have a function that takesAsync<'a>
and handles errors in a standard way. Maybe you have a function that takes anAsync<seq<'a>>
and validates that the list isn’t empty.You honestly don’t need a special name just for the thing that fetches one kind of thing.
Congratulations on making the very good choice to try F#!
To answer your question in yet another way:
@Asik already mentioned using a function instead of a single-method interface. This idea may very well be extended to having records which group a bunch of related functions together; for example:
It’s always possible to use interfaces as well, but I like this method better because it’s easier to mock (just assign
Unchecked.defaultof<_>
to any fields the test code won’t use) and because the syntax looks much nicer, among other things.If you need nested dependencies (which you surely will), you can simply use closures:
You essentially provide the dependencies to a factory function and then the dependencies will be captured in the lambdas’ closures, allowing you to nest dependencies as deeply as need be. This pattern of using factory functions works quite well with ASP.Net’s built-in DI container too.
First, as @Karl Bielefeldt has been pointed out, the correct type to return here is
Async<seq<Category>>
. So your function originally should be of typeWCRestEndpoint -> Async<seq<Category>>
.But that’s not the real issue here. The real issue is this claim:
This claim does not make any sense at all to me because refactoring is actually simpler in the F# case.
No matter how you code this, you’re always going to need to write code that takes a
WCRestEndpoint
and outputs a sequence ofCategory
s. If you decide that you’re actually going to get the sequence ofCategory
s in some other way, then you’re going to need to write new code to do this no matter what.For example, let’s suppose I decide I need to modify my code to get categories from a
OtherCatGetter
instead of aWCRestEndpoint
. In your C# code, I would need to replacewith
We would also have to replace every single call to
new WcCategoryService(wcRest)
with a call tonew OtherCategoryService(getter)
.On the
F#
side, we would have to replacewith
and replace every occurence of
GetCategoriesFromWC wcRest
with an occurence ofgetCategoriesFromOther getter
.Clearly, it’s the F# version that requires less refactoring when you need to change how you’re getting your
Category
s, since F# doesn’t have to deal with the boilerplate of defining a new public class with a single read-only field and a one-argument constructor. If you need to define a different way of getting a sequence ofCategory
s, you just do it rather than jumping through unnecessary hoops.