mark.warren
2018-6-15 13:30:29

In Racket/Scheme is dependency injection seen as idiomatic?

For example if you have a function that uses a random number it is easier to test if the random number generator is supplied to the function as you can supply a known sequence for your tests.

Basic example

(define (random-example) (random 10))

(define (random-example2 generator-lambda) (generator-lambda 10))

usage

(random-example)

(random-example2 (λ (x) (random x)))


samth
2018-6-15 13:31:23

@mark.warren probably the idiomatic way to do things like that would be a parameter


samth
2018-6-15 13:31:42

and/or an optional argument to random


samth
2018-6-15 13:32:16

in fact, that’s how random works already — it takes an optional second argument which is the generator, and the default behavior is to look up the current value of a parameter


mark.warren
2018-6-15 13:36:28

@samth Thank you, I was using random as an example, but that information is good to know. I was wondering really if DI is idiomatic Racket.


samth
2018-6-15 13:39:44

I feel like dependency injection means a lot of things to different people


samth
2018-6-15 13:39:55

but the pattern that random uses is pretty idiomatic


mark.warren
2018-6-15 13:40:45

@samth Indeed you are correct. I think I see what you are getting at now. Have an optional argument so that you can supply the generator if you want else use the default.


samth
2018-6-15 13:41:09

and also you can change the default for a whole bunch of code with parameterize


mark.warren
2018-6-15 13:41:24

Thanks