Tuesday, 28 May 2013

NO Side Effects

I’ve heard of side-effects before. Uncle Bob? He ‘ates ‘em.  I’m totally paid up on the benefits of removing them too. Clean Code. But in the Scala world, they’re more than a nice to have. The core of the language expects you to avoid them, and so, it seems incredibly relevant to state clearly what a side effects are:

“A function or expression is said to have a side effect if, in addition to producing a value [a return type], it modifies some state or has an observable interaction with calling functions or the outside world. A function might modify a global or a static variable, modify one of it’s arguments [without taking a copy first – think about the pitfalls of pass-by-value with objects in Java], raise an exception, write data to a display or file, read data, or call other functions having side effects.”

Scala in Action, Nilanjan Raychaudhuri, Chapter 1

Now that all sounds great.  Especially the implication that, with no side effects you can always determine a program’s behaviour.  But a closer look sends my head reeling. How do I handle exceptional circumstances if I can’t thrown an exception? How do I do any meaningful work if I can’t read from or write to files (or, I guess, other things like network resources)?  I’m guessing there will be some kind of Functional “Get Out of Jail Free” way around this, or into it.  Of everything I’ve encountered so far, this is the biggest mind shift – and one which, when grasped, will definitely have a positive effect on my attempts at Bob-friendly code.