Pluggability in a functional paradigm - f#

What is the proper functional way to handle pluggability in projects? I am working on a new opensource project in F# and can not seem to get the object oriented idea of plugins and interfaces out of my mind. Things I would like to be able to swap out are loggers, datastoring, and authentication.
I have been searching quite a bit for an answer to this and havent come up with much except for this:
http://flyingfrogblog.blogspot.com/2010/12/extensibility-in-functional-programming.html

The answer to this question would be different for different functional languages. F# is not purely functional - it takes the best from functional, imperative and also object-oriented worlds.
For things like logging and authentication, the most pragmatic approach would be to use interfaces (in F#, it is perfectly fine to use interfaces, but people do not generally use inheritance and prefer composition instead).
A simple interface makes sense when you have multiple different functions that you can invoke:
type IAuthentication =
abstract Authenticate : string * string -> bool
abstract ResetPassword : string * string -> void
You can use object expressions, which is a really nice way to implement interfaces in F#.
If you have just a single function (like logging a message), then you can parameterize your code by a function (which is like an interface with just a single method):
type Logger = string -> unit
For things like authentication and logging (that probably do not change while the application is running), you can use a global mutable value. Although if you want to synchronize requests from multiple threads and there is some mutable state, it might be a good idea to write an F# agent.

Related

F# and protected access modifier [duplicate]

Is there a better way of modeling data in F# to avoid needing it?
The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected member, the following code could be surprising:
type Base() =
protected member x.Test(a) = a > 10
type Inherited() =
inherit Base()
member x.Filter(list) =
list |> List.filter (fun a -> x.Test(a))
This code wouldn't work, because you're calling Test from a lambda function (which is a different object than the current instance of Test), so the code wouldn't work. I think this is tha main reason for not supporting the protected modifier in F#.
In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?
As to whether F# enables a better way of modeling data, signature files allow finer grained visibility decisions than internal does in C#, which is often very nice. See Brian's comment here for a little bit more explanation. This is independent of support (or lack thereof) for protected, though.

ocaml, Functors : dependency injection

In Real World Ocaml Chapter 9 which is about functors :
Dependency injection
Makes the implementations of some components of a system swappable. This is particularly useful when you want to mock up parts
of your system for testing and simulation purposes.
But I fail to grasp the idea.
I also looked at Wikipedia about DI - but I actually do not catch the relaton with testing and simulation purposes.
Dependency injection is a software engineering technique, whose purpose is to reduce the interdependencies between two subsystems of a program. A very important detail of this technique, is that it involves not two, but three subsystems:
a service,
a client using a
an injector, whose responsibility is to prepare a service for a client.
The latter subsystem, with its responsibility, an often overlooked but crucial detail: this implies that the client knows as little about the service as its public interface, which means that one can easily use a mocked service to test the client.
Assume that we write an application communicating with a key-value store over the network. The key-value store has the following signature:
module type AbstractKeyValueStoreService =
sig
exception NetworkError
type t
val list : t -> string
val find : t -> string -> string option
val set : t -> string -> string -> unit
end
If we write our client code as a client parametrise by a module of type AbstractKeyValueStoreService we can test the resilience of our application to network errors when using the set function by just providing a mocked service, without needing to actually create the network error:
module KeyValueStoreServiceFailingOnSet =
struct
exception NetworkError
type t = unit
let list () = [ "a"; "b"]
let find = function
| "a" -> Some("x")
| "b" -> Some("y")
| _ -> None
let set _ _ = raise NetworkError
end
If our client is written as functor parametrised by a module of type AbstractKeyValueStoreService it is easy to write tests for this software component, where a mocking service follow a more-or-less complex interaction script with the client.
Using modules as parameters might not be an “earth shaking idea” it is nevertheless important to be aware of how this idea can be used to solve important software engineering problems. This is what the authors of “real world OCaml” seem to do.
It seems to me they're just trying to show how the term "dependency injection" can be seen to refer to parameters that are full modules. And that's what OCaml functors are: modules with parameters that are also modules.
This has many uses, not just testing and simulation. But certainly you can use it for those. For example, you can use it to supply a "mock" module during testing, to replace some part of the system that's difficult to reproduce exactly in the test environment.
One way to look at this is that "dependency injection" isn't as interesting or novel as its adherents might want you to think. At least that's what I think personally. Using modules as parameters isn't an earth shaking idea, it's been around for decades in the ML languages. In Angular (at least), this is mixed up with a separate notion, that of having the names of function parameters be semantically meaningful. That (IMHO) is a mistake.

How to not touch my DI container for every new method in Api Controller when using f#

I am trying to wrap my head around how to handle DI in F# when using WebApi with something like Ninject.
For example, in C# when i wire up my container I would simply tell the DI what the type resolves to, for example:
kernel.Bind<ISomeInterface>().To<SomeClass>();
My Api Controllers will automatically wire this when required by the controllers constructor.
Great, now I can add methods to the interface & class all day long w/o touching the container again.
However in F# (unless i am doing this completely wrong) I create partial applications and then pass them to the controller, every time I add a method i have to wire up again at the container. Maybe this is correct, I am not sure but it seems like a lot more wiring.
To clarify what I mean, lets take a typical REST Api. For each entity with CRUD - so for example:
Customer (Create, Read, Update, Delete).
Would I then have to inject each function into the controller?
So in this example, lets say that i have the service -> domain -> repo model:
let createCustomerFunc = createCustomerDomainFunc createCustomerRepoFunc
let getAllCustomersFunc = getAllCustomerDomainFunc getAllCustomerRepoFunc
let updateCustomerFunc cust = [...]
let deleteCustomerFunc id = [...]
let getSingleCustomerFunc id = [...]
Now in my container when i bind it, i would then do something like:
kernel.Bind<CustomerController>().To<CustomerController>()
.WithConstructorArgument(createCustomerFunc, getAllCustomerFunc, etc...)
|> ignore
Now if i add method: GetActiveCustomers I would then have to modify my code above to pass in the new partial application?
That feels ... wrong - am i simply approaching this incorrectly?
Using a DI Container provides some advantages, as well as some disadvantages.
The major advantage is that, if you have a large code base, you can use convention over configuration to wire up all the dependencies. With convention over configuration, you also get the benefit that your code will have to be more consistent, because it has to follow conventions.
There are several disadvantages, though. The most immediate is that you lose the rapid feedback from the compiler. You can much easier make a change to your system, and while everything compiles, the system fails at run-time. Some people hope that you can ask a DI Container to self-diagnose, but you can't.
Another, less apparent, disadvantage of using a DI Container is that it becomes too easy, as you say, to simply add more members to Controllers, etc. This actually increases coupling, or reduces cohesion, but the Reflection-based automation provided by DI Containers hides this problem from you.
Since I believe that the disadvantages outweigh the advantages, I recommend that you use Pure DI instead of DI Containers.
This goes for Object-Oriented Programming in C#, Visual Basic .NET, or Java, but applies equally to Functional Programming in F#.
In an unmixed Functional F# code base, I wouldn't use classes or interfaces at all; instead, I'd only compose functions together.
In a mixed code base with e.g. ASP.NET Web API, I'd cross the bridge between OOP and FP as quickly as possible. As I explain in my Test-Driven Development with F# talk (expanded material available on Pluralsight), I'd inject a function into a Controller like this:
type ReservationsController(imp) =
inherit ApiController()
member this.Post(rendition : ReservationRendition) : IHttpActionResult =
match imp rendition with
| Failure(ValidationError msg) -> this.BadRequest msg :> _
| Failure CapacityExceeded -> this.StatusCode HttpStatusCode.Forbidden :> _
| Success () -> this.Ok () :> _
That's the entire code base of that Controller. All behaviour is implemented by imp.
In the startup code of the application, imp is composed like this:
let imp =
Validate.reservationValid
>> Rop.bind (Capacity.check 10 SqlGateway.getReservedSeats)
>> Rop.map SqlGateway.saveReservation
You may argue that the above ReservationsController only defines a single Post method. What if a Controller has to expose more methods?
In that case, inject an implementation function per method. In a REST API, any Controller only ought to have 2-3 methods anyway, so that means, in effect, 2-3 dependencies. In my opinion, that's a perfectly acceptable number of dependencies.
The reason for the 2-3 method maximum is that in proper RESTful design, resources tend to follow a few interaction patterns:
GET
POST
POST, GET
PUT, GET
DELETE, GET
PUT, DELETE, GET
The full combination (POST, GET, PUT, DELETE) is a REST design smell, but all of that is an entirely different discussion.
Fundamentally, you are using functional code style in a object oriented framework. Since WebAPI required you to instantiate a controller, you have to bridge the OO to functional approach somehow.
Setting function values in a DI container is a rather awkward approach, since you have to manually bind to the constructor arguments. I would recommend an adapter pattern based approach, that is create a class to wrap the (static) function calls.
pub type CustomerFunctionAdapter() =
member x.CreateCustomer = createCustomerFunc
member x.GetAllCustomers = getAllCustomersFunc
// ...
and still bind with
kernel.Bind<ISomeInterface>().To<CustomerFunctionAdapter>();
This way, your changes and additions are in CustomerFunctionAdapter, rather that in your DI bindings.

How to swap functions (e.g.for tests) in pure functional programming

I'm trying to understand what is an FP-alternative to good old dependency injection from OOP.
Say I have the following app (pseudocode)
app() is where application starts. It allows user to register and list user posts (whatever). These two functions are composed out of several other functions (register does it step by step, imperatively, while list posts really composes them (at least this is how I understand function composition).
app()
registerUser(u)
validate(u)
persist(u)
callSaveToDB(u)
notify(u)
sendsEmail
listPosts(u)
postsToView(loadUserPosts(findUser(u)))
Now I'd like to test this stuff (registerUser and listPosts) and would like to have stubbed functions so that I don't call db etc - you know, usual testing stuff.
I know it's possible to pass functions to functions e.g
registerUser(validateFn, persistFn, notifyFn, u)
and have it partially applied so it looks like registerUser(u) with other functions closed over and so on. But it all needs to be done on app boot level as it was in OOP (wiring dependencies and bootstraping an app). It looks like manually doing this will take ages and tons of boilerplate code. Is there something obvious I'm missing there? Is there any other way of doing that?
EDIT:
I see having IO there is not a good example. So what if I have function composed of several other functions and one of them is really heavy (in terms of computations) and I'd like to swap it?
Simply - I'm looking for FP way of doing DI stuff.
The way to answer this is to drop the phrase "dependency injection" and think about it more fundamentally. Write down interfaces as types for each component. Implement functions that have those types. Replace them as needed. There's no magic, and language features like type classes make it easy for the compiler to ensure you can substitute methods in an interface.
The previous Haskell-specific answer, shows how to use Haskell types for the API: https://stackoverflow.com/a/14329487/83805

Why isn't there a protected access modifier in F#?

Is there a better way of modeling data in F# to avoid needing it?
The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected member, the following code could be surprising:
type Base() =
protected member x.Test(a) = a > 10
type Inherited() =
inherit Base()
member x.Filter(list) =
list |> List.filter (fun a -> x.Test(a))
This code wouldn't work, because you're calling Test from a lambda function (which is a different object than the current instance of Test), so the code wouldn't work. I think this is tha main reason for not supporting the protected modifier in F#.
In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?
As to whether F# enables a better way of modeling data, signature files allow finer grained visibility decisions than internal does in C#, which is often very nice. See Brian's comment here for a little bit more explanation. This is independent of support (or lack thereof) for protected, though.

Resources