Musings of a Long Distance Runner: What is Immutable?

About a 18 months ago I decided not to be the kind of programmer who sits on his backside all day getting frustrated and angry at code not working properly, and never exercising. I had long ago stopped going for coffee at the gym regularly enough to retain the gym membership that comes with my medical aid and although I play for a Sunday league football team, I had mastered the ability to look busy while not really doing much and letting the other ten members of my team do useful things.

The obvious option was running, and I took to it like a duck to water. Toxic water. Highly toxic water that makes you breathe like a 50 a day man, while crying rivers of sweat. Eventually, in the physical exertion version of Stockholm Syndrome, I came to love my captor. I completed local park runs without embarrassing myself, and eventually took on trail running and lengthy road runs. Now I am the kind of programmer who still gets frustrated and angry at code not working properly, but goes for a run in between, which brings me to the point, albeit via a lengthy route (ironically).

While on one of these runs, I happened to be accompanied by a friend of mine, who we shall call Riaan (for that is his name). Riaan is also a developer. Riaan is also introverted. Riaan also doubts his abilities as a developer from time to time. I assume that every other developer in the world is outgoing and supremely confident in their abilities, and its just a strange quirk of the universe that has thrown us together, but I digress. While discussing the terrifying world of programming, he mentioned that he was aware of holes in his knowledge, and that while he didn’t have the time or finances (despite the efforts of the fees must fall movement) to do another degree, he had the possibility of further training through a contract he was working on, and was keen to do something to tighten up on his knowledge. We discussed what courses or level of course he might look for, and at some point he mentioned wanting to get clarity on various things that come up in his day to day work, and gave the example of immutablity (yup, that sound you just heard was me colliding with the point a mere three paragraphs in).

Now I’ve been swotting up as much as possible of late including a fair amount of reading on design patterns and other abstract concepts that cause my brain to ache and inevitably ends with me shouting at my children. I reckoned I had vague understanding of what Immutable “things” were. Without breaking stride I told Riaan that I would present my findings to him at some point in the future, and, as they say in the movies (possibly) the future is now.

Lets start with what Immutable isn’t.

My sons are immutable. You literally cannot shut them up. However, this is mute in the sense of “I wish you were a mute because you have been screaming for the last hour and my head hurts”. So put all thoughts of the word “mute” out of your head along with any wishes for children with a mute button.

The Teenage Mutant Ninja Turtles are mutants. We aren’t talking about mutants today. I will do my best to write a post on the similarities between the Teenage Mutant Ninja Turtles and Object Orientated Programming in the future, mainly because it might trick my sons into thinking I have an interesting life, but not today sunshine. Put your half shell away, and untie that purple bandana (and if you even contemplate dressing up as anyone other than Donatello, maybe the tech world isn’t for you).

So what is it then genius?

If a “thing” is Immutable it cannot be changed.

We use the term “immutable” for two reasons (both of which I just invented and probably aren’t true):

  1. Ichangeable sounds like a lazy guess at how to say “changeable” in Xhosa
  2. Mutants are cool (see previous point)

So our metaphorical “thing” can’t be mutated and therefore is Immutable. Just like Donald Trump’s IQ, it is the way it is now and forever and will not change.

Immutable Variables

In the following example, the variable $name is mutable as it can be changed.

$name = "John";
$name = "Paul";
echo "The best Beatle was {$name}";

Lets say that, like me, you think that there is no way on God’s green earth that Paul was better than John.

define( 'NAME', 'John' );
// If you even attempt define( 'NAME', 'Paul' ); or NAME = 'Paul'; your code debugger is going to find you and beat you more times than the word "Jude" is repeated in Hey Jude.
echo 'The best Beatle was ' . NAME;

Good luck getting through that one Paul. Any attempt to redefine the NAME constant throws an error and everyone points and stares. Just to push the point home, here it is in again in JavaScript (and because Riaan was specifically referring to JavaScript during our run):

// Mutable
var name = "John";
name = "Paul";
console.log( "The best Beatle is " + name );
// Immutable
const name = "John";
// If you even attempt const name = "Paul"; or name = 'Paul'; your code linter is going to find you and beat you so hard that the lyrics to I am the Walrus will start making sense.
console.log( "The best Beatle is " + name );

Immutable Functions

While mulling over this post, and how I would manage to write anything vaguely knowledgeable on the subject, I happened to listen to the Syntax podcast on “Buzz Words”, and in a tremendous example of the universe favouring me and pouring good fortune down upon me (making a change from its default setting for the substance it rains down on me), Wes Bos and Scott Tolinski picked “Immutable / Mutable / Mutations” as one of the 22 buzz words they discussed. Wes gives the great example of splicing and slicing arrays with slice being an immutable function as it does not change the array it is applied too, while splice is mutable because it does.

Here’s an example. In an effort to prove that I am contemporary, I will use the names of a more modern beat combo than The Beatles (I was born in 1979 so I’m not quite sure where that previous example came from).

This:

var oneDirection = [
  "The one that quit and made my friends daughter cry",
  "Harry Styles",
  "The other one",
  "Er, is there a fourth one too?"
];

var newDirection = oneDirection.slice( 1 );

console.log( oneDirection );
console.log( newDirection );

would output:

["The one that quit and made my friends daughter cry", "Harry Styles", "The other one", "Er, is there a fourth one too?"]
["Harry Styles", "The other one", "Er, is there a fourth one too?"]

This is an immutable function as the original oneDirection array remains unchanged (as I’m sure the original One Direction do in many of our hearts), while the newDirection array reflects the hollow loneliness of a cruel future without the one that left.

Splice is a whole different kettle of mutable fish though. Splice has no time for fond memories. You leave oneDirection and you’re dead to Splice. History.

Splice has a cold cruel heart, and likes pulling the legs off of small insects:

var oneDirection = [
  "The one that quit and made my friends daughter cry",
  "Harry Styles",
  "The other one",
  "Er, is there a fourth one too?"
];

var newDirection = oneDirection.splice( 1, 3 );

console.log( oneDirection );
console.log( newDirection );

Read it and weep cruel deserter:

["The one that quit and made my friends daughter cry"]
["Harry Styles", "The other one", "Er, is there a fourth one too?"]

Immutable Objects

Immutable objects traditionally have their properties set by their constructor. Their properties are private and have no public setter methods. I say “traditionally” because I am sure there are multiple exceptions to this, and I’m just too lazy to go to page 2 of my google results for “please help me look clever and explain immutable objects”.

If my wife was an object, her state would be set to “right” and it would be impossible to change this state at any point. Ever.

class Wife {

  private $am_i_wrong;

  public function get_am_i_wrong() {
    return $this->am_i_wrong;
  }

  public function __construct( $am_i_wrong ) {
    $this->am_i_wrong = $am_i_wrong;
  }
}

$my_wife = new Wife( 'No' );

echo "Is my wife wrong? ";
echo $my_wife->get_am_i_wrong();
// Is my wife wrong? No;

Note that there is no way of changing the $am_i_wrong variable. This instance of $my_wife is right forever and there’s nothing you can do about it. You can create $your_wife and make her wrong, but $my_wife is right. I would include a code example for this, but if I type “new Wife” again, I may lose teeth.

This is a very basic example and there are ways around it (unlike my wife who is complex and cannot be fooled by simple tricks), for more detail, take a read of this excellent post on immutability in PHP.

Further, slightly less well researched, thoughts

Riaan uses Angular a lot. Unfortunately my expertise lies more in React over Angular (i.e. I did the React Tic Tac Toe tutorial once and have yet to do the equivalent Angular tutorial), but I would assume there are a lot of similarities in how state is handled across both libraries. The React tutorial goes into specifics about how tracking changes and allowing users to skip back several moves is made vastly simpler by using new copies of a data object rather than mutating the original.

Conclusion

Either Riaan, feels like he knows all things immutable now or he’s feeling reassured that he may have holes in his knowledge, but he hasn’t just made a complete pigs-ear of trying to explain them publicly. Either way, he talked me into doing the Trail du Mont Rochelle 18km last weekend, and my legs still aren’t talking to me so he’s on his own.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.