jueves, 16 de junio de 2011

Abstractions in Scala

There is an ongoing discussion regarding abstraction in programming. Some people say "Always abstract it" and other people argument that you have to start doing something at some point, you can't keep thinking in the clouds, you must get something done. There is a very long thread in the Scala mailing list so I won't enter into details here.

I understand the pragmatism, i.e. "get it done" which is fair enough given we don't have unlimited time to ponder on the abstract and mathematics. The thing is most people are missing a really important detail: someone else has already done the abstractions for us!!!

By intuition an abstraction groups some stuff and generalizes it, the higher you go the less useful abstractions you are able to find, it's like a pyramid. An useful abstraction doesn't come up every week, the more abstractions we have, the harder it gets to create new ones and go up the pyramid one more step. All we have to do is learn the current known pyramid, *we* don't have to live and work on the abstract (unless we want to write scientific papers).

In the land of Scala we have Scalaz. At first it's daunting, the main problem is that even if you can look through the code there is so much stuff that you simply don't get the point of it or don't even know how you would use it. It's actually not hard to understand, honestly, you just have to learn the purpose behind the stuff in there.

From the point of view of a complete newbie in this high level stuff I found these the most useful, compact and simple resources on the matter:

Nick Partridge at the Melbourne Scala User Group: http://vimeo.com/10482466

In there we are shown in real time how to go from a method summing the elements of a List[Int] into folding any Monoid without using Scalaz and coding it on the fly and thus learning the thinking behind this library.

And finally, the holy grail, the Typeclassopedia, I don't know why people don't throw it to you on the face every time you ask about Monads, Arrows and other Typeclasses and get it done with. There you will understand the purpose of all the typeclasses in Scalaz. (Don't mind the Haskell, text is clear enough to get you going even if you don't fully understand the code)

After the minor effort of working through these you will begin to *see* abstractions, you don't have to abstract stuff away, you will only have to use the new tools you have which are already coded in Scalaz. You will not waste time, you will save time. And most importantly even if you don't use Scalaz you should start thinking different about code and will just get better at it.

Bottom line, you don't have to think how to make stuff more abstract, you just have to know that the stuff you are doing already has an abstraction done for you.