Perfecting Code Reviews

I first read about the Core Protocols way back in the early 2000s from Jim & Michele McCarthy’s book “Software for your head”.

book cover

They seem like a sensible set of ideas but probably way too radical for most organizations. I recall we tried adopting the protocols with a team I was leading a few years later but due to other constraints it didn’t entirely succeed.

Like all great ideas, it came back to me again while listening to the agile weekly podcast in the early 2010’s. I had not thought about them again or had another opportunity to try using them with a new team until recently when talking to a friend about code reviews.

Describing how I do code reviews with another developer, I noticed during the conversation that I had been subconsciously using the Perfection Game in recent sessions. It was in an adapted form to suit the medium but still captured the spirit of the original.

Perfection

The Perfection Game is used as a way to help you improve something you have created. It’s at a time when you are asking for help in making something better so that the exercise becomes more collaborative than critical.

Perfect results by thinking and telling one another what you like and what would make the results perfect.

It starts with the creator (or perfectee) presenting something to someone else, asking that person to rate the performance on a scale of 1 to 10. The perfector then lists the things they liked about the performance and offers suggestions for improvement that would take the work from it’s current score to a “10”. If the perfector can’t think of a way to improve the code, they can’t withhold points.

Review

Code reviews, by contrast, can be very negative experiences, particularly for less experienced developers presenting code to world-weary, battle-scarred bad-ass senior devs. A more experienced developer looking at the code may be tempted to start straight into statements pretending to be questions - “why did you do it that way?”, “that’s all wrong, why would you write it like that?”, “why didn’t you think about…?”, “how can that ever work?” etc.

The less experienced developer often have a lot of anxiety about others reading their code and may strongly identify with their code and feel very protective of it, may be hurt by ill considered comments or withdraw from further interactions. There’s probably a whole series of articles on using techniques, like the Socratic method, to teach self evaluation of source code.

Steps

Here’s how I approach code reviews now using my covert perfection game :)

  • Person asks for code review
  • Person explains the reason for the change
  • Person demonstrates the change
  • Person shows diffs between old and new code

During this process I am making notes on things I think could be improved, things which may be wrong, things which they may not have considered. I have a running total in my head of the “score” I think I want to give. At the end, I’ll say something like: “I would give that change a 7 out of 10”. I would then ask for permission to share my thoughts for how it could be improved (no is always an acceptable answer). Then I would suggest concrete improvements to be made to bring the score up to full marks. This might be a suggestion of how to make something more robust but might be as vague as “that name doesn’t convey what you are hoping it would, how can we make it better reflect your intention?”

Conclusion

It seems to be working well and I think I might keep it.

You can see the core protocols at the McCarthy website or download a pdf.

A Bicycle for the Mind

I think one of the things that really separates us from the high primates is that we’re tool builders. I read a study that measured the efficiency of locomotion for various species on the planet. The condor used the least energy to move a kilometer. And, humans came in with a rather unimpressive showing, about a third of the way down the list. It was not too proud a showing for the crown of creation. So, that didn’t look so good. But, then somebody at Scientific American had the insight to test the efficiency of locomotion for a man on a bicycle. And, a man on a bicycle, a human on a bicycle, blew the condor away, completely off the top of the charts.
And that’s what a computer is to me. What a computer is to me is it’s the most remarkable tool that we’ve ever come up with, and it’s the equivalent of a bicycle for our minds.

Steve Jobs

Building a sketchbook

Book making and bookbinding is a skill I knew nothing about but find fascinating so I thought I would have a go at building a cheap and cheerful A5 sketchbook with a cover. Here’s how I did it.

Find some paper. The internals of the book is paper, of course.

step 1

For A5 format, I folded 20 sheets of A4 in half to form a set of nested pages.

step 2

In book binding terms this is called a signature. I am only making a simple sketchbook so I am only going to use one signature. If you use more, the book will be thicker but you then need to start investigating sewing and binding techniques. That’s another project for me.

step 3

Notice how the pages don’t fit together perfectly, one inside the other. They sort of bulge out more as you go towards the centre. The more pages you have in a signature, the worse this gets. Don’t worry, we’ll fix this in a little while.

Once you have a signature, we need to assemble some tools. Some staples to keep the pages together and something to make holes for the staples because a standard stapler isn’t built to work with this thickness of paper or where the holes are required to be.

step 4

We also need a cover for the sketchbook. Wilkinsons sell 10 sheets of black card that’s thick enough for our purposes and it costs around £1.25 a pack.

step 4a

Mark the positions of the staples. Measure in from the outer edges of the sketchbook about an inch and make a pencil mark on the inner sheet of paper at the fold. Use the staples as a guide to mark a second hole so that both sets of pencil marks show where you need to puncture through all the paper and through the cover.

step 5

Use your tool of choice, bradawl or whatever, to make holes in the paper from the inner sheet to the outer in all four places. Be careful to keep all the sheets aligned so that the staples will fit correctly with no misplaced sheets.

step 7

Fold the A4 cover sheet in half and wrap it around the signature. Make four holes in the cover to line up with the holes in the signature.

Fit the staples through the four holes at top and bottom, from the outside cover into the book.

step 8

Bend the ends of the staples to keep the book together.

step 9

The book should now look something like this, it should open and close freely.

step 10

On close inspection, you will see that where the sheets of paper have been nested inside one another, the edges of the book are not aligned and go out in a kind of v-shape. This needs to be trimmed down.

step 11

Use a cutting mat and a sharp craft knife to trim the edges of the inner pages to line up with the outer most pages and the cover. This might also apply to the top and bottom of the sheets, depending on the relative sizes of the paper and the outer cover.

step 12

Your book should now close with no pages sticking out.

step 13

step 14

Now I have a good idea of how this basic version works, I may try some more elaborate designs and builds for other sketchbooks. Watch this space.

Gall's Law

A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over with a working simple system.

John Gall

Lettering Kata

I am a big fan of katas and the idea of deliberate practice in general so one thing I have not done the whole time I’ve been involved in sketchnoting is any kind of practice lettering to try to increase the diversity of typefaces I have available to me with minimal effort.

This is a copy of an exercise I saw somewhere but can’t recall where - probably on twitter maybe?

lettering kata

Visual Studio Code Snippets FTW

I think I had mostly forgotten about lots of little features in Visual Studio, like code snippets. Today I was updating some unit tests from NUnit 2.X to the most recent version of NUnit because there are quite a few breaking changes. For example the ExpectedException attribute is no longer supported and has been replaced with an Assert. I think this is a positive change for the code but it meant that a lot of code needed to be migrated from one form to the other, from an attribute above the method to a code change within it.

The original code was like this:



[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Calling_Api_With_Null_Not_Allowed()
{
	// next line should cause an exception to be thrown.	
	MyApi.CallMethod(null);
	// expecting not to get here
}


and it needed to look like this:



[Test]
public void Calling_Api_With_Null_Not_Allowed()
{
	Assert.That(() =>
	{
		MyApi.CallMethod(null);
	},
	Throws.Exception.TypeOf<ArgumentNullException>());
}


Not a big change, but not something that can be done as a search and replace which would have been nice given the spread of the original code throughout our existing tests. The code for each test needs to be inspected to see where the exception is expected and code above and below sometimes needs to be cleaned up or removed. This was fiddly enough that I found I created a template in notepad so that I could switch between that and the code to cut and paste into each method. Part way through it occurred to me that we should really have a refactoring for this and remembered that a few years ago, at a different job, I had used code snippets and templates to do some of this kind of automation. Rather than finding something in the refactoring section of Visual Studio’s Edit menu, under Intellisense (or from a right-click context menu) there is Insert Snippet… (Ctrl+K, X) and Surround With… (Ctrl+K, S).

The surround with option gives you some options you might expect #if, do, while, if etc., the very things you think about in code that wrap around something else.

surround

Unfortunately, there wasn’t one for what I wanted. Hmmm. Knowing Visual Studio, I thought there was probably a mechanism to extend those and I was right. Under Tools\Code Snippets Manager there are a series of code snippets for each language.

surround

I used one of these built-in snippets as a template to create my own NUnit surround. I called it


<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>throws</Title>
			<Shortcut>throws</Shortcut>
			<Description>Code snippet for assert throws exception</Description>
			<Author>Derek Graham</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
				<SnippetType>SurroundsWith</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Code Language="csharp"><![CDATA[Assert.That(() =>
            {
				$selected$ $end$
			},
            Throws.Exception.TypeOf<System.Exception>());]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

You can save it to the same folder as Visual Studio’s (under program files) or put it under My Code Snippets (under My Documents).

Once it’s installed and VS has restarted, the Surround With menu includes the new snippet:

surround

The whole thing took me 20 minutes at most and meant I was able to complete the refactor work in about 1/10 of the time I was expecting it to take. Visual Studio code snippets FTW! I will be definitely exploring what else we can do with these snippets and maybe look at refactoring snippets too.

Minecraft Detectorists

Another simple minecraft game, this time using Pythagoras’ theorem to work out distances between two points.

We randomly bury a piece of treasure - a gold block, a diamond, whatever - then give the player clues about how far away they are from it. The “game” ends when they dig up the block.


import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import random
import math

def random_underground_position():
  return minecraft.Vec3(random.randint(-100, 100), random.randint(-20, 0), random.randint(-100, 100))

def distance_to_treasure(player, treasure):
  dx = player.x - treasure.x
  dy = player.y - treasure.y
  dz = player.z - treasure.z
  return math.ceil(math.sqrt((dx*dx) + (dy*dy) + (dz*dz)))
  
world = minecraft.Minecraft.create()

treasure = random_underground_position()
world.setBlock(treasure.x, treasure.y, treasure.z, block.GOLD_BLOCK)

last_position = world.player.getTilePos()
last_distance = distance_to_treasure(last_position, treasure)

world.postToChat("Find the gold!")

detectoring = True

while detectoring:

  position = world.player.getTilePos()
  
  if position != last_position:
    distance = distance_to_treasure(position, treasure)
  
    if distance < 5:
      detectoring = False
    else:
      message = ""
	  
      if distance < last_distance:
        message = "Warmer " + str(distance)
      elif distance > last_distance:
        message = "Colder " + str(distance)
      
      world.postToChat(message)

    last_distance = distance 

  last_position = position
  time.sleep(2)

world.postToChat("You found the treasure")
  

Inspired by code I originally saw at Martin O’Hanlon’s excellent Stuff About Code.

It's Raining Blocks

A super simple rain simulator creates blocks at random positions in the sky and lets them fall to the ground under minecraft physics.


import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import random

world = minecraft.Minecraft.create()

while True:

  x = random.randint(-100, 100)
  y = 100
  z = random.randint(-100, 100)
  
  world.setBlock(x, y, z, block.WATER)
  time.sleep(random.randint(1, 5))


The slightly weird thing about this is the “rain” is much more like a waterfall. A single block stays in place in the sky and just leaks water downwards until it reaches the ground and then just sort of pools.

If you don’t like water, you could substitute ice blocks or even lava, Dante’s Peak style. Lava has different properties to water (no kidding!) in that it takes on a little bit more life and starts to bubble up and grow from wherever it was left.

This is a pretty “destructive” script in that it leaves a lot of messy blocks all over the world so you probably want to run it in a world that you don’t mind throwing away afterwards.

Microbit coin flipper

Running up to a new Maker’s week at the end of July, I was getting a bit bored with the tamagotchi example that uses the accelerometer gestures (shake) to wake up a virtual pet. When the pet is asleep it shows a sleepy icon and you can shake it awake for a few seconds, when it shows a happy face.

I came up with a similar idea to simulate a coin toss using shaking and showing one of two images based on heads or tails.


# random coin flipper
from microbit import *
import random

while True:

    display.show(Image.NO)
    
    if accelerometer.was_gesture('shake'):
        coin = random.choice(['heads', 'tails'])
        
        if coin == 'heads':
            display.show(Image.SKULL)
        else:
            display.show(Image.SQUARE)
            


Strong Style Pairing

I’m a big fan and advocate for mob programming and have talked about it quite a bit. At the heart of mob programming is the idea of Strong-style pairing.

For an idea to go from your head into the computer it MUST go through someone else's hands

This is how I like to think about it:

strong style sketchnote