When embracing functional programming principles in languages that aren’t designed specifically for functional programming, dealing with side effects requires great care and discipline. For those who can’t remember what side effects are, side effects are attempts to modify the state of the world (at least in terms of the scope of your program’s environment) through a means other than the return value of a function (e.g., performing a SQL insert, printing text to the standard output device, sending an email, etc.) Hopefully you noticed the word “attempts.” The problem with trying to directly modify the state of the world is that you don’t know what state the world is in: sometimes we’re caught by surprise.
I try to compartmentalize side effects in functions that lack branching constructs (e.g., if/then, switch, etc.) I refer to this type of function as a fall-through function because the function proceeds line-by-line until it reaches the last line and returns the status or result. Here’s a simple example of a fall-through function in PHP that sends an email:
<?php $mail = function($to, $subject, $message){ // handle longer lines $message = wordwrap($message, 70, "\r\n"); // send message, returning status return mail($to, $subject, $message); }; ?>
Fall-through functions provide clean separation of the logic we want to test from the world-dependent states that are unpredictable (i.e., code containing side effects), and as we know, clear boundaries are a good thing.
Leave a Reply to Jamal Cancel reply