3 ms·
Mark Seemann's blog I've been reading for the past couple years answers this question. In particular, his posts on Hexagonal Architecture[0] and Dependency Reje
by ItsMonkk 6y ago
Mark Seemann's blog I've been reading for the past couple years answers this question. In particular, his posts on Hexagonal Architecture[0] and Dependency Rejection[1], but there are many more articles that cover this and I highly endorse reading.
To summarize, you want to set up your code into two distinct categories, data and pure functions. Your data is at the top level of your code, so if you need external data that needs to be at the top level of your module. You then feed that data through a pipeline of pure functions that return with some sort of answer back to your top level module that can then pass into some other function(or through a quick lambda) that does the actual transformation at the top level. The key is that a function can either be a pure function or it can be an impure function. Never both.
As an example, let's say you've got code that has to read from a couple text files. Currently your code does this through a couple nested loops, with the loops passing in what folder it is in and what its file name is, but your code is filtering through some that you don't want to read.
To re-envision this code, you would create a pure function that comes back to the top of your module of which files to read. Then that top module would read those files, and pass them to some other function that does transformations on the result.
You now don't have to create mocks, just create data and pass that into your pipeline and then check if it gets the expected result. One of the interesting side effects of doing this, is at a certain point you stop unit testing for correctness(as the code is so easy to reason about written in this style), and start unit testing primarily for documentation.
[0]: https://blog.ploeh.dk/2013/12/03/layers-onions-ports-adapters-its-all-the-same/ https://blog.ploeh.dk/2013/12/03/layers-onions-ports-adapter...
[1]: https://blog.ploeh.dk/2017/02/02/dependency-rejection/ https://blog.ploeh.dk/2017/02/02/dependency-rejection/