[Haskell-beginners] "pure" versus "impure" code
shaleh at speakeasy.net
Fri May 20 07:27:39 CEST 2011
On May 19, 2011, at 1:12 PM, Costello, Roger L. wrote:
> Also, it is my understanding that good software design is to isolate/separate the impure code from the pure code. Is that correct? Does that principle apply to all programming languages, or just Haskell?
(Since you asked about other languages the code below is pseudo Python, but Haskell, C, whatever would still work)
The question is why you would want to make this separation. At first blush it sounds arbitrary. In fact for writing code quickly in a "throw away" mode that kind of separation is over kill in other languages. But consider code you might want to keep for a few years.
Let's consider a typical hacking problem. You need to read from a file and do something. The something is not all that important.
for line in file:
# parse / edit / print / something
Now let's say you have this chunk of code in the middle of some function calls. Now to test this code you have to have access to a filesystem with the file ready to go. What if you just checked out the code from revision control? Guess you need to checkout the test data too. Bummer.
If we abstract out the concept of reading from a file we could provide a fake file interface and still test our code. You can imagine how this would help test networking code and other types of I/O.
In haskell this can be accomplished by hiding a Handle in your own type and for testing providing a different Handle which is not bound to I/O. But you can also separate the code which deals with the result of the input from the act of doing the I/O.
input = 
for line in file:
# do something with input over here
Now we can test all of the code which simply acts on the input data. We can provide our own canned data, etc. Due to the IO Monad this is a bigger concern for Haskell but it is good programming practice in any language.
More information about the Beginners