13 July 2015

What is the skv prefix and when to use it

I came up with the skv prefix sometime during 2014 and it has been readily adopted by the team so I wanted to share it with you. Our team uses a rough approximation of Hungarian notation as our naming convention and adding skv was definitely our best mod to the popular standard.

skv stands for "Structure of Key-Pair Values" and is used for objects in Javascript, associative arrays in PHP and structs in ColdFusion that do not have any methods and can therefore be converted to a JSON string without losing anything. Distinctly different to objects (that we prefix with obj) which have methods which would be lost during serialisation/encoding to a string notation.

(Note: The skv prefix is not used for standard numeric arrays which are prefixed with arr)

Example time...

PHP (some server-side page that returns plain-text JSON)

<?php
// Set the content type for good practice
header('Content-Type: application/json');

// Create a variable with some information about a monkey
$skvMonkey = array(
    "strName" => "Martin",
    "numBananas" => 7
);

// This feels right! We're not destroying anything
echo json_encode( $skvMonkey, true );
?>

Javascript (in browser)

<script>
// AJAX call to PHP page returns object
var skvMonkey = ajaxCallToPHP();

// Hazaar! This variable has everything it did when it was server-side and I know it has no (non-native) methods because it is not prefixed with obj!
console.log( skvMonkey.strName );
</script>

We tend to pass a lot of complicated datasets back and forth between Javascript and server-side pages (or caches). Serialising these bundles of information as JSON allows us to strongly bind the variable name and the variable value, making our code more robust and quicker to debug. However, I was frustrated by the lack of distinction between an object that could be safely JSONified and those that could not.

Objects (or components) are like high-tech vending machines full of colourful sweets. Their methods are the coin-operated interfaces that instruct mechanical arms to pick out exactly the right chocolate bar, deliver it to the easily accessible letterbox and sort the remaining products. Pushing something as beautiful as that into a JSON converter feels like bribing a thug to smash the glass with his fist, tip all the sweets into a sack and burn the machine. Using the skv prefix is basically a green light to a developer to say "this is just a box of sweets, you can be rough with it, I've packed it really well".