Friday, March 15, 2013

Church and State

It's been a while. Which means I've probably been having too much fun doing other stuff.

We recently saw the election of a new Pope, and I was thinking about some countries which embed their religion into the law of the land. The USA makes a big deal about separation of church and state, and I think that's a good thing.

 In software we often make a token effort to separate things. How many people remember their first program in college looking something like

            StreamReader streamReader = new StreamReader(_fileName);
            while (streamReader.Peek() >= 0) {
                string line = streamReader.ReadLine();
                if (line != null){
                    IEnumerable data = parseLine(line);
                    double sum = 0;
                    foreach (double d in data){
                        sum += d;

So right from the start, we teach kids to bind Where we get the data, What we do with it, and Where we send the results.

Separation of functionality?

  • We could get the data and pass in an iterator
  • We could wrap the stream in a class which implements an IEnumerable
  • We could write a separate class parse Class, and pass it in.
  • We could write a separate sum() action and pass that in.
  • We could return the result as an iterator, which would execute as we step through.
We could end up with 4 separate, useful small classes which could be reused and mixed to suit our needs.

We could even hand off the Loop to Linq.
Imagine the resulting code

            enumerableFile = new EnumerableFile("sample.txt");

            var results = enumerableFile.Select(
                    s => ParseStringToDoubleList.parseLine(s).Sum()

Now I can write unit tests for ParseStringToDoubleList() - Ok, an appalling name, but that's an others days work.

I can use Linq's Sum function.

If I want averages instead, no problem. 

I now have a tool-kit to build functionality

First we learn to build programs, then we learn to build tools to make better programs. 

No comments:

Post a Comment