83 points · by luu · 11y ago · 68 comments
Watch it if you still haven't
http://www.haskellforall.com/2012/07/purify-code-using-free-...
I think there is sort of a hole in the logic about testing though, since the article talks about testing `runPure` not `run` which is almost useless unless `run` is implemented in terms of `runPure` which introduces its own can of worms because you have to consider how things like laziness, streaming, etc. come into play in the pure version, which is a step in the wrong direction IMO.
What the article says about reasoning is important, but I feel like it's misleading to say that it comes from the using the free monad. It's really about the Functor instance. The fact that `ExitSuccess >> m = ExitSuccess` is a result of the Functor instance for TeletypeF not using (and not being able to use) the `f` parameter in the `fmap f ExitSuccess` definition.
If you don't want to use a free monad, you could also use a type class / monad transformer like `MonadTeletype` which defines the actions of the teletype can perform. Then you write all your teletype functions with a signature like `MonadTeletype m => .... -> m a`. You still get the guarantee that no arbitrary actions are there but you don't have the complexity of the free monads which can be a little daunting for newer Haskellers.
But the code is indeed easier to verify for correctness, due to the purity. I wish this style of programming is more prevalent, but alas, it's more difficult to write this way...there aint no free lunch
Monads are only needed when the output of one action determines the next action to take. If you already have a list of which actions you're going to take, you don't need a monad.
Why it is ultra testable I didn't get, though. To me it looks like what you should do in normal mode not ultra mode.
The article starts with discounting mocks, and later describes how you should hand-code them each time.
The author's point is to avoid interleaving logic and side-effects (as much as possible) in the first place. Yes, we can use dependency injection to send mocks deep into the bowels of our application where they get called. Alternatively, we can have the bowels of our application return values, describing what to call, back up to the top of our application. These are exactly dual.
The nice thing about the latter is that every action gets reified into a concrete value, on which we can perform any kind of computation we like. Dependency injection can't do that, since a method call is not a value (it can return a value, but it isn't itself a first-class value).
Mocks allow us to inspect which calls have been made, etc. but mocks are for testing. We can't use those interfaces in our real code. If we use a list-of-actions we can, for example, run optimisation passes before execution.
> they do all that without requiring you to create a new DSL for capturing and describing effects.
Mocks do require a new DSL for capturing and describing effects; it's normally called a "public interface", but it is a DSL (an algebra) for describing effects.
But with mocks you're not really interleaving side effects. They are the same as generating "effect values", only they use the same API as the actual effect.
> The nice thing about the latter is that every action gets reified into a concrete value, on which we can perform any kind of computation we like.
That's what mocks do. They capture calls and turn them into reified values that can then be manipulated and queried.
> Mocks do require a new DSL for capturing and describing effects; it's normally called a "public interface", but it is a DSL (an algebra) for describing effects.
Except that API is identical to that of whatever effect API we're using.
A mock is a mechanism for turning effects into values. It just works automatically by means of interfaces (in the language sense) and reflection. It is an imperative construct that achieves -- without extra work -- the very same functional effect the author is striving for.
Yes, you are. Side effects aren't limited to filesystems, databases, etc. Here's the very first sentence of http://en.wikipedia.org/wiki/Side_effect_(computer_science)
> In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world.
Every time we call a mock, we cause observable changes (ie. we alter the results of any queries made on the mock). Therefore, calling a mock is a side-effect.
The point of mocking is to replace unwanted side-effects with harmless side-effects. The side-effects are still there, mixed in with the logic.
> That's what mocks do. They capture calls and turn them into reified values that can then be manipulated and queried.
But mocks are only used in tests! My application can't ask, say, a FileSystem object for a list of calls which have been made. Only my tests can do that, because they're using a FileSystemMock object instead. My application can't use a FileSystemMock since, by design, it can't do the filesystem manipulation that I need.
Even if I add call-logging to the API of my FileSystem object, it doesn't give me any control, since they've already happened by the time they appear in my queries.
For example, let's say my application ends up with a list of effect values [e1, e2, e3, etc.] and, after performing some logic, it chooses to only return the first one: [e1].
How would mocks help me do this? Firstly, since this is application code rather than test code, I can't use mocks at all. Secondly, even if I could perform a query to get [call1, call2, call3, etc.], there's no way to turn that into [call1]; I can remove the logs of call2, call3, etc. but I can't undo any side-effects they've caused.
To achieve the same outcome as the effect value example, I must alter the control flow of the program such that call2, call3, etc. are never made. That has nothing to do with mocking.
> Except that API is identical to that of whatever effect API we're using.
Exactly! How is an "effect API" not a DSL for describing effects? They're the same thing. Mocks don't
It's not supposed to be easy. Doing it well is really hard and way underappreciated.
>Testing side-effecting code is hard. This is well established. It's also convoluted, complex, generally brittle.
It's not necessarily brittle when done right but it's hard, it's convoluted and it's complex.
>Before the test, create the input AND go to the filesystem, prepare the input and the spot where output is expected. After the test, check the output AND go to the filesystem, read the files from there and check their contents. Everything is intertwined: the prep, the implementation of the code under test, and the checks at the end. It's specific to my filesystem. And it's slow. No way can I run more than a few of these each build.
This doesn't sound like it would take more than a few hundred milliseconds. That's not slow.
Furthermore, you could definitely run it on multiple filesystems by firing up a virtual machine for each filesystem and running the test. That would be slow, but you don't need to do it often.
If a single test takes a few hundred milliseconds then that means you can only run a dozen or so such tests before you hit that problem, which isn't very many. I'd say that a few hundred milliseconds is quite slow in this context.
I don't think that's a problem at all. I usually run one functional test at a time while developing (ideally runtime < 30 seconds) which covers the code that I'm changing.
90% of the bugs that I introduce accidentally will get picked up by that test while I'm refactoring.
In the background (often on a different machine) I will have the full set of tests running constantly. Those might take hours to complete (sometimes a whole night). They will pick up the 5-10% of bugs that slipped through the net eventually, though - which is ok.
This is way better than having a unit test suite that doesn't even come close to mimicing real life usage, and is a PITA to maintain because it's naturally tightly coupled to your architecture (this bites you back when you refactor).
>If a single test takes a few hundred milliseconds then that means you can only run a dozen or so such tests before you hit that problem, which isn't very many. I'd say that a few hundred milliseconds is quite slow in this context.
One 500 millisecond test for this particular use case will pick up 90% of bugs. No, that is not going to interrupt your development cycle.
Yes, a full suite of tests that fires up a VM for every different possible kind of filesystem will take hours. That's perfectly ok. You can go get a coffee while it runs.
Sometimes it's just not practical to impose a hard limit of "a few seconds at most" on your test suite, especially for larger projects. (some projects have test suites that take hours to run, and simply cannot be any quicker unless they were less thorough).
> [...] run it on multiple filesystems by firing up a virtual machine for each filesystem
Yeah... I can see what you mean by not supposed to be easy.
But this is good too.
it's beautiful in theory. but reality goes like this: "i only have this little method. writing mocks will take 5x more time then the code. i will just test the side effects on the functional tests"
then, a year later, the team added a dozen methods that would benefit from the mock, but since you did the first one in functional only, the team just added the new ones there as well.
the end. (because nobody refactor projects for tests)
:(
Furthermore side effects have nothing to do with testing one's code. Why? Because you have to test your own logic, not I/O or something else. I/O is already tested by someone else. So you actually don't care where the data comes from - the filesystem or a hardcoded string - you care if the output is correct after the respective transformations are applied to the input.
And when you think about it testing shouldn't be that needed at all. In the OOP world, where state and identity are helplessly tied together and we are not working with values, but with references to values, tests might be a necessary evil.
In the land of Functional however writing tests shouldn't be needed, at least in theory. Why? Because if you write small composable functions you should be able to test them right in the REPL. Corner cases? You have to think about them right from the start. TDD forces you to do so - then why shouldn't you when you have the immense power of a REPL? Once a function is ready you are not supposed to change it much. If you do you should change the inner workings and not the input/output. If you need to change the i/o most probably you need a different function. But what is more important is that if you needed to change the i/o and had tests for this function you would actually need to change the tests as well, which is more work (double? triple?) and no added value.
This presupposes that you will always come up with an adequate design, and that you won't have to refactor this library of functions. For large enough systems, this is almost never the case. For sizeable systems in production, you will always come up against things you haven't thought of before.
Granted, proper factoring of your functions in the first place is going to help a lot. (Small composable functions.) However, if you claim that you can code such that you never ever have to change your mind about function signatures, never have to propagate changes across the system, even in large production systems, then you're either not seeing something, or you have some technique which you should be selling or basing a consulting practice around. (And/or, maybe I have something new to learn.)
EDIT: I have written projects in Clojure, including a multiplayer game server. This is the experience I'm basing this comment on.
Then: Granted, proper factoring of your functions in the first place is going to help a lot. hence -> Once a function is ready you are not supposed to change it much. much not= at all.
And you are absolutely correct - eventually you will have to change some of your functions. And when you need to do so you should focus on the logic and take your time until you understand it completely. Only then refactor the funciton. So the emphasis should be on the developer completely understanding the task and not on the developer finding a cheap way to change the code and rely on tests to catch his errors.
Furthermore if you change the signature of a function, tests are just another place where you need to change the function as well. In practice the tests that you wrote are not doing you any good because you cannot test the reinvented function with the old set of tests.
Sure, tests might catch a few errors here and there at some point. But after all what is more time consuming - maintaining hundreds of thousands of tests or focusing on your single, small, composable function and your problem?
I am part of a team that develops a very large .NET (with C#) product with hundreds of projects in the solution. So far the primary use of tests is to be maintained. They caught a few bugs, true, but nothing that our QAs were not going to see anyway. In imperative OOP land tests are a necessary evil, but with time I started doubting even that thesis.
One thing I've found is that what would help tremendously with large production projects results from epiphenomena in code, and is sometimes not what is sexy from a language design standpoint.
I am part of a team that develops a very large .NET (with C#) product with hundreds of projects in the solution. So far the primary use of tests is to be maintained. They caught a few bugs, true, but nothing that our QAs were not going to see anyway.
I was a fly on the wall when Extreme Programming was being formulated in Smalltalk. (Not part of the Chrysler C3 project, but I was working for a Smalltalk vendor and heard about what was going on.) Test Driven Development, or at least good Unit Test coverage, is essential for an agile style project in a language like Smalltalk. I'm not so sure unit tests are as essential for languages like C#. TDD does produce more testable code, but it has considerable "cultural overhead."
Two important questions to ask are: What aids refactoring? What stops refactoring? The answers to these questions are also different for large codebases as opposed to small ones. I have noticed that Swift's enums are tremendously useful in this regard, but they are not "sexy" so this doesn't get discussed very much.
In this specific example, if you write the first file, but fail the second, you might want to undo the write to the first file. Or write another file to say you failed. Or write to a log. These sorts of things are important, and mocks can be a good way to fake it.
Btw in functional languages catching exceptions is not idiomatic, it breaks the functional approach.
In this example you are not supposed to test undoing the file. Undoing (deleting) is what I/O does and this part is tested by someone else, somewhere else. You only need to test the arguments that are passed to that specific I/O function. If they are correct your program is correct. If they are hardcoded you shouldn't be testing them at all.
You may want to write a log. Again, test what you are about to pass to an I/O function. Don't test if the file is actually written. If you supply the I/O function with the correct arguments and the function fails to write the file, the issue is not in your code - search for it elsewhere.
Your approach seems to be "the IO happens somewhere else". I'm not sure that that's much more of a compliment.
I do this in Clojure, but am looking to migrate to Haskell soon to enforce this even further.
I suppose you will be migrating to Haskell because it is a PF language. What would you miss most from Clojure once you migrate?
Tests are very useful for distinguishing between "what a function does" and "what you think a function does". Especially when you're building on functions written by others. Types and documentation help too, but if someone's already misunderstood something, such descriptive information might still fit nicely with their incorrect world view.
Personally, I can't live without QuickCheck :)
In any case: in a functional programming language, you'd just unit test the building blocks (functions). Assuming every function is pure and total, these unit tests should be succinct and mirror your business logic quite closely.
Yes, when people say that no tests are needed, it's hyperbolic. Tests are always needed, but you do not need to test all corner cases, just the ones created by business logic.
if you write clean, data driven code i can't imagine this ever being a problem you need to solve.