Refactoring the code on my billing system, I was promoting a method to its parent object. If I did it right, the output from the code wouldn’t be any different before and after the refactor.
Unfortunately, the output page was a large table of numbers, and it was difficult to detect a small change at a glance. If only there were some way to have the page spit out a checksum, I could quickly tell whether the refactor resulted in identical output.
SHA-1 is an encryption algorithm. It takes a string of any length as an input and returns a string of 20 hexadecimal characters. It’s easy to reduce a big HTML table full of numbers to a small string.
It was still a little difficult to tell the difference between, for example, the next two lines
a847a906c9955734217c348eaa5b3b38abab0bdf 15b8fdd026c607e0b51b2d5e51103a77bf103354
So I decided to take advantage of the fact that here was a nice long string of hex decimals. I grabbed the first 6 and the last 6 digits to create a colored box with a colored border. Now I could quickly glance at a big blob of color and tell whether anything had changed.
This difference is much easier to see:
15b8fdd026c607e0b51b2d5e51103a77bf103354 a847a906c9955734217c348eaa5b3b38abab0bdf
Here is the PHP function:
function getVisualChecksum($out)
{
// from boulderinformationservices.wordpress.com
$checksum = sha1($out);
$checksumColor1 = substr($checksum, 0, 6);
$checksumColor2 = substr($checksum, -6, 6);
return sprintf(
'<span style="background-color: #%s; border: 4px solid #%s">%s</span>',
$checksumColor1,
$checksumColor2,
$checksum
);
}