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.
Related
I've read about Reader Monad from this article by Jorge Castillo himself and I've also got this article by Paco. It seems that both tackles the idea of Dependency Injection just in a different way. (Or am I wrong?)
I'm really confused whether I understand the whole Reader Monad and how it relates to the Simple Depenency Injection that Paco is talking about.
Can anyone help me understand these two things? Would I ever need both of them in one project depending on situations?
Your doubt is understandable, since yes both approaches share the same outcome: Passing dependencies implicitly for you all the way across your call stack, so you don't need to pass them explicitly at every level. With both approaches you will pass your dependencies once from the outer edge, and that's it.
Let's say you have the functions a(), b(), c() and d(), and let's say each one calls the next one: a() -> b() -> c() -> d(). That is our program.
If you didn't use any of the mentioned mechanisms, and you needed some dependencies in d(), you would end up forwarding your dependencies (let's call them ctx) all the way down on every single level:
a(ctx) -> b(ctx) -> c(ctx) -> d(ctx)
While after using any of the mentioned two approaches, it'd be like:
a(ctx) -> b() -> c() -> d()
But still, and this is the important thing to remember, you'd have your dependencies accessible in the scope of each one of those functions. This is possible because with the described approaches you enable an enclosing context that automatically forwards them on every level, and that each one of the functions runs within. So, being into that context, the function gets visibility of those dependencies.
Reader: It's a data type. I encourage you to read and try to understand this glossary where data types are explained, since the difference between both approaches requires understanding what type classes and data types are, and how they play together:
https://arrow-kt.io/docs/patterns/glossary/
As a summary, data types represent a context for the program's data. In this case, Reader stands for a computation that requires some dependencies to run. I.e. a computation like (D) -> A. Thanks to it's flatMap / map / and other of its functions and how they are encoded, D will be passed implicitly on every level, and since you will define every one of your program functions as a Reader, you will always be operating within the Reader context hence get access to the required dependencies (ctx). I.e:
a(): Reader<D, A>
b(): Reader<D, A>
c(): Reader<D, A>
d(): Reader<D, A>
So chaining them with the Reader available combinators like flatMap or map you'll get D being implicitly passed all the way down and enabled (accessible) for each of those levels.
In the other hand, the approach described by Paco's post looks different, but ends up achieving the same. This approach is about leveraging Kotlin extension functions, since by defining a program to work over a receiver type (let's call it Context) at all levels will mean every level will have access to the mentioned context and its properties. I.e:
Context.a()
Context.b()
Context.c()
Context.d()
Note that an extension function receiver is a parameter that without extension function support you'd need to manually pass as an additional function argument on every call, so in that way is a dependency, or a "context" that the function requires to run. Understanding those this way and understanding how Kotlin interprets extension functions, the receiver will not need to be forwarded manually on every level but just passed to the entry edge:
ctx.a() -> b() -> c() -> d()
B, c, and d would be called implicitly without the need for you to explicitly call each level function over the receiver since each function is already running inside that context, hence it has access to its properties (dependencies) enabled automatically.
So once we understand both we'd need to pick one, or any other DI approach. That's quite subjective, since in the functional world there are also other alternatives for injecting dependencies like the tagless final approach which relies on type classes and their compile time resolution, or the EnvIO which is still not available in Arrow but will be soon (or an equivalent alternative). But I don't want to get you more confused here. In my opinion the Reader is a bit "noisy" in combination with other common data types like IO, and I usually aim for tagless final approaches, since those allow to keep program constraints determined by injected type classes and rely on IO runtime for the complete your program.
Hopefully this helped a bit, otherwise feel free to ask again and we'll be back to answer 👍
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.
Does Swift provide a native Design by Contract support? I understand that it can be done during runtime through assertions, but could it be done during compile time? Or, are there any external plugins/libraries that do this?
EDIT
By saying "during compile time Design by Contract", I do not mean the library to be an all powerful static analyser that C# has. It would be enough for me if it is something like the one that iContract provides for Java. Let us look at an example:
A DBC code for the square root evaluation in Java using iContract could be written as :
/**
* #pre f >= 0.0
* #post Math.abs((return * return) - f) < 0.001
*/
public float sqrt(float f) { ... }
Now, this keeps my contract as a part of my API specification rather than a part of its implementation which I believe is a cleaner way. The caller will know what his responsibilities are and the callee is setting its expectation, all in albeit clearer manner. Do we have something like this in Swift?
TL;DR
As #Tommy points out in the comments under your question, it would appear that the plain & simple answer to your question is "No, compile time DbC is not currently a feature of Swift".
What's built in right now?
For built-in support for this type of design strategy, you currently have to look at the runtime I'm afraid. Swift appears to prefer runtime assertions for enforcing preconditions currently, although the language seems generally to be putting more emphasis on safety at compile time (more on this below). The global functions assert, assertionFailure, precondition and preconditionFailure are designed to be sprinkled liberally throughout code without impacting release build performance.
Unit tests are, of course, another strategy for checking that API contracts are fulfilled, but these must be thought of and implemented manually, and so are error prone.
Something else that is perhaps interesting to note is that amongst the better documentation comment support of Swift 2, "requires", "precondition" and "postcondition" are recognised markup keywords, such that they are displayed prominently in quick help documentation:
/// - precondition: f >= 0.0
/// - postcondition: abs((return * return) - f) < 0.001
/// - returns: The square root of `f`.
func sqrt(f: Float) -> Float { ... }
So does this emphasis on being able to provide good documentation for API contracts mean that the Swift development team clearly cares about it, and this is a stop-gap until they incorporate something into the syntax in the future, or does it mean that they think this sort of information belongs in the documentation? Pointless postulation, perhaps. Regardless, despite the fact it's not proper DbC, I think it's a handy thing to be aware of right now.
What can I do about it now?
With Objective-C, macros could be used to essentially implement basic DbC, however the lack of macros in Swift means you would have to resort to some kind of function/generics-based wrapper, which I think would look like a really awkward bodge.
Xcode's support for adding custom scripts to a target's build phases – as suggested by #JonShier in the comments – is perhaps the closest you will get to useful & automatic DbC without waiting for the language to (maybe / maybe not) introduce such a feature. With the aforementioned documentation markup keywords, a script that analyses documentation comments to build unit tests could even be incorporated retrospectively to projects with only a small amount of learning/effort on the part of the user. As you say, I think this could make a very interesting project!
Will it be a built-in feature in the future?
It is not clear whether or not native DbC might be incorporated into Swift in the future. Arguably, it is a feature that is well suited to the mission of the Swift language, which is to say that it promotes safer code and reduced risk of runtime errors. Should it become a part of the language, I would suggest that we would be more likely to see them appear as declaration attributes than as interpreted comment markup, for example:
#contract(
precondition = f >= 0.0,
postcondition = abs((return * return) - f) < 0.001
)
func sqrt(f: Float) -> Float { ... }
(But that is just speculation, and of no use to us right now!)
From what I know of the topic, compile-time DbC can be a very complex problem. But who knows... work on the Clang Static Analyzer has certainly shown that there is an underlying desire to drag identification of runtime bugs back to compile time. Perhaps this is the perfect problem to put a Swift static analyser to work on in the future?
I'm not if this is what you're looking for but here is a suggestion you could try maybe.
If you want to define a protocol where you can define the signature of the sqrt function and leave the implementation for other classes or structs to implement at a later point you could do something like the code below:
Note: the the sqrtf is just using the system implementation here.
public protocol Math {
func sqrtf(f: Float) -> Float
}
struct NativeMath: Math {
func sqrtf(f: Float) -> Float {
return sqrt(f)
}
}
println(NativeMath().sqrtf(2))
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.
I've not been able to find a robust, general op_Dynamic implementation: can anyone point me to one? So far searches have only turned up toys or specific purpose implementations, but I'd like to have one on hand which, say, compares in robustness to C#'s default static dynamic implementation (i.e. handle lots / all cases, cache reflection calls) (it's been a while since I've looked at C#'s static dynamic, so forgive me if my assertions about it's abilities are false).
Thanks!
There is a module FSharp.Interop.Dynamic, on nuget that should robustly handle the dynamic operator using the dlr.
It has several advantages over a lot of the snippets out there.
Performance it uses Dynamitey for the dlr call which implements caching and is a .NET Standard Library
Handles methods that return void, you'll get a binding exception if you don't discard results of those.
The dlr handles the case of calling a delegate return by a function automatically, this will also allow you to do the same with an FSharpFunc
Adds an !? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime.
It's open source, Apache license, you can look at the implementation and it includes unit test example cases.
You can never get fully general implementation of the ? operator. The operator can be implemented differently for various types where it may need to do something special depending on the type:
For Dictionary<T, R>, you'd want it to use the lookup function of the dictionary
For the SQL objects in my article you referenced, you want it to use specific SQL API
For unknown .NET objects, you want it to use .NET Reflection
If you're looking for an implementation that uses Reflection, then you can use one I implemented in F# binding for MonoDevelop (available on GitHub). It is reasonably complete and handles property access, method calls as well as static members. (The rest of the linked file uses it heavily to call internal members of F# compiler). It uses Reflection directly, so it is quite slow, but it is quite feature-complete.
Another alternative would be to implement the operator on top of .NET 4.0 Dynamic Language Runtime (so that it would use the same underlying API as dynamic in C# 4). I don't think there is an implementation of this somewhere out there, but here is a simple example how you can get it:
#r "Microsoft.CSharp.dll"
open System
open System.Runtime.CompilerServices
open Microsoft.CSharp.RuntimeBinder
let (?) (inst:obj) name (arg:'T) : 'R =
// Create site (representing dynamic operation for converting result to 'R
let convertSite =
CallSite<Func<CallSite, Object, 'R>>.Create //'
(Binder.Convert(CSharpBinderFlags.None, typeof<'R>, null)) //'
// Create site for the method call with single argument of type 'T
let callSite =
CallSite<Func<CallSite, Object, 'T, Object>>.Create //'
(Binder.InvokeMember
( CSharpBinderFlags.None, name, null, null,
[| CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) |]))
// Run the method and perform conversion
convertSite.Target.Invoke
(convertSite, callSite.Target.Invoke(callSite, inst, arg))
let o = box (new Random())
let a : int = o?Next(10)
This works only for instance method calls with single argument (You can find out how to do this by looking at code generated by C# compiler for dynamic invocations). I guess if you mixed the completeness (from the first one) with the approach to use DLR (in the second one), you'd get the most robust implementation you can get.
EDIT: I also posted the code to F# Snippets. Here is the version using DLR: http://fssnip.net/2U and here is the version from F# plugin (using .NET Reflection): http://fssnip.net/2V