What is simple code? Everyone has a different definition but I think we can draw some universal distinctions. I was thinking of this the other day when I read a nice LtU post about complexity. It had a couple of semantically equivalent code examples. I'm going to pull them over here to make a point.

Here's low simplicity (in C++):

float *miles_to_kilometers(float *mile_list, int length) {

float *kilo_list = new float[length];

for(int i = 0; i < length; i++) {

kilo_list[i] = mile_list[i] * 1.61;

}

return kilo_list;

}



Higher simplicity (in Perl):

sub miles_to_kilometers {

my @result = map { $_ * 1.61 } @{$_[0]};

return @result;

}

And extremely high simplicity (in Haskell):

milesToKilometers = map (* 1.61)

Low simplicity is characterized by the use of widely understood constructs. A first year CS student would have no trouble understanding the C++ example.

The Perl example is uses a higher level abstraction, map, so it's relatively opaque if you don't know what a map is, but once you do, you can appreciate the simplicity.



The Haskell version.. well what can I say about Haskell? It's a profoundly elegant language but it's opaque if you don't have the requisite understanding.

The Haskell version uses a functional language style called "point free" programming. It defines a function called milesToKilometers that accepts a list and applies map to it with an anonymous function that multiplies each element by 1.6. If you're wondering where the list is in the definition, don't. It's not there. The Haskell type system is advanced enough to infer types for you, so you can leave off the list argument. The compiler knows that milesToKilometers can accept a list because map accepts one.

Bewildering? Yes, but it's also simple -- once you understand it.

That's the difference between low simplicity and high simplicity -- you have to work to understand high simplicity. But, high simplicity isn't defined just by the amount of work you have to do. If it was, all of the crufty code that we've ever scratched our heads over would be simple. We know that's not the case.

You have high simplicity when you can take something away from that work.. something that makes the next thing you encounter easier to understand. The map pattern is one of these things, and point-free programming is another. Languages will differ in their support for these constructions but there's a lot of value in knowing them, regardless of what language you use. High simplicity is concise, and it rides on top of simple well-defined abstractions.

