Question

I have been doing SOLID in C# to a pretty extreme level in recent times and at some point realized I'm essentially not doing much else than composing functions nowadays. And after I recently started looking at F# again, I figured that it would probably be the much more appropriate choice of language for much of what I'm doing now, so I'd like to try and port a real world C# project to F# as a proof of concept. I think I could pull off the actual code (in a very un-idiomatic fashion), but I can't imagine what an architecture would look like that allows me to work in a similarly flexible fashion as in C#.

What I mean by this is that I have lots of small classes and interfaces that I compose using an IoC container, and I also use patterns like Decorator and Composite a lot. This results in an (in my opinion) very flexible and evolvable overall architecture that allows me to easily replace or extend functionality at any point of the application. Depending on how big the required change is, I might only need to write a new implementation of an interface, replace it in the IoC registration and be done. Even if the change is bigger, I can replace parts of the object graph while the rest of the application simply stands as it did before.

Now with F#, I don't have classes and interfaces (I know I can, but I think that's beside the point when I want to do actual functional programming), I don't have constructor injection, and I don't have IoC containers. I know I can do something like a Decorator pattern using higher order functions, but that doesn't quite seem to give me the same kind of flexibility and maintainability as classes with constructor injection.

Consider these C# types:

public class Dings
{
    public string Lol { get; set; }

    public string Rofl { get; set; }
}

public interface IGetStuff
{
    IEnumerable<Dings> For(Guid id);
}

public class AsdFilteringGetStuff : IGetStuff
{
    private readonly IGetStuff _innerGetStuff;

    public AsdFilteringGetStuff(IGetStuff innerGetStuff)
    {
        this._innerGetStuff = innerGetStuff;
    }

    public IEnumerable<Dings> For(Guid id)
    {
        return this._innerGetStuff.For(id).Where(d => d.Lol == "asd");
    }
}

public class GeneratingGetStuff : IGetStuff
{
    public IEnumerable<Dings> For(Guid id)
    {
        IEnumerable<Dings> dingse;

        // somehow knows how to create correct dingse for the ID

        return dingse;
    }
}

I'll tell my IoC container to resolve AsdFilteringGetStuff for IGetStuff and GeneratingGetStuff for its own dependency with that interface. Now if I need a different filter or remove the filter altogether, I may need the respective implementation of IGetStuff and then simply change the IoC registration. As long as the interface stays the same, I don't need to touch stuff within the application. OCP and LSP, enabled by DIP.

Now what do I do in F#?

type Dings (lol, rofl) =
    member x.Lol = lol
    member x.Rofl = rofl

let GenerateDingse id =
    // create list

let AsdFilteredDingse id =
    GenerateDingse id |> List.filter (fun x -> x.Lol = "asd")

I love how much less code this is, but I lose flexibility. Yes, I can call AsdFilteredDingse or GenerateDingse in the same place, because the types are the same - but how do I decide which one to call without hard coding it at the call site? Also, while these two functions are interchangeable, I now cannot replace the generator function inside AsdFilteredDingse without changing this function as well. This isn't very nice.

Next attempt:

let GenerateDingse id =
    // create list

let AsdFilteredDingse (generator : System.Guid -> Dings list) id =
    generator id |> List.filter (fun x -> x.Lol = "asd")

Now I have composability by making AsdFilteredDingse a higher order function, but the two functions are not interchangeable anymore. On second thought, they probably shouldn't be anyway.

What else could I do? I could mimic the "composition root" concept from my C# SOLID in the last file of the F# project. Most files are just collections of functions, then I have some kind of "registry", which replaces the IoC container, and finally there is one function that I call to actually run the application and that uses functions from the "registry". In the "registry", I know I need a function of type (Guid -> Dings list), which I'll call GetDingseForId. This is the one I call, never the individual functions defined earlier.

For the decorator, the definition would be

let GetDingseForId id = AsdFilteredDingse GenerateDingse

To remove the filter, I'd change that to

let GetDingseForId id = GenerateDingse

The downside(?) of this is that all functions that use other functions would sensibly have to be higher order functions, and my "registry" would have to map all functions that I use, because the actual functions defined earlier can't call any functions defined later, in particular not those from the "registry". I might also run into circular dependency issues with the "registry" mappings.

Does any of this make sense? How do you really build an F# application to be maintainable and evolvable (not to mention testable)?

Was it helpful?

Solution

This is easy once you realize that Object-Oriented Constructor Injection corresponds very closely to Functional Partial Function Application.

First, I'd write Dings as a record type:

type Dings = { Lol : string; Rofl : string }

In F#, the IGetStuff interface can be reduced to a single function with the signature

Guid -> seq<Dings>

A client using this function would take it as a parameter:

let Client getStuff =
    getStuff(Guid("055E7FF1-2919-4246-876E-1DA71980BE9C")) |> Seq.toList

The signature for the Client function is:

(Guid -> #seq<'b>) -> 'b list

As you can see, it takes a function of the target signature as input, and returns a list.

Generator

The generator function is easy to write:

let GenerateDingse id =
    seq {
        yield { Lol = "Ha!"; Rofl = "Ha ha ha!" }
        yield { Lol = "Ho!"; Rofl = "Ho ho ho!" }
        yield { Lol = "asd"; Rofl = "ASD" } }

The GenerateDingse function has this signature:

'a -> seq<Dings>

This is actually more generic than Guid -> seq<Dings>, but that's not a problem. If you only want to compose the Client with GenerateDingse, you could simply use it like this:

let result = Client GenerateDingse

Which would return all three Ding values from GenerateDingse.

Decorator

The original Decorator is a little bit more difficult, but not much. In general, instead of adding the Decorated (inner) type as a constructor argument, you just add it as a parameter value to a function:

let AdsFilteredDingse id s = s |> Seq.filter (fun d -> d.Lol = "asd")

This function has this signature:

'a -> seq<Dings> -> seq<Dings>

That's not quite what we want, but it's easy to compose it with GenerateDingse:

let composed id = GenerateDingse id |> AdsFilteredDingse id

The composed function has the signature

'a -> seq<Dings>

Just what we're looking for!

You can now use Client with composed like this:

let result = Client composed

which will return only [{Lol = "asd"; Rofl = "ASD";}].

You don't have to define the composed function first; you can also compose it on the spot:

let result = Client (fun id -> GenerateDingse id |> AdsFilteredDingse id)

This also returns [{Lol = "asd"; Rofl = "ASD";}].

Alternative Decorator

The previous example works well, but doesn't really Decorate a similar function. Here's an alternative:

let AdsFilteredDingse id f = f id |> Seq.filter (fun d -> d.Lol = "asd")

This function has the signature:

'a -> ('a -> #seq<Dings>) -> seq<Dings>

As you can see, the f argument is another function with the same signature, so it more closely resembles the Decorator pattern. You can compose it like this:

let composed id = GenerateDingse |> AdsFilteredDingse id

Again, you can use Client with composed like this:

let result = Client composed

or inline like this:

let result = Client (fun id -> GenerateDingse |> AdsFilteredDingse id)

For more examples and principles for composing entire applications with F#, see my on-line course on Functional architecture with F#.

For more about Object-Oriented Principles and how they map to Functional Programming, see my blog post on the SOLID principles and how they apply to FP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top