Thursday, April 7, 2016

I prefix my variables with their type!

Why 'Systems Hungarian' makes sense.

As a developer, if you prefix the variable type you are clearly in the minority - I for one am a propoment of Systems Hungarian and belong to that group myself.

The merrits become apparent when reading other people's code, or when you look at your own code months/years after. Properly naming variables is hard, the type is not always obvious and left to individual interpenetration. Prefixing completely removes any uncertainty, it immediately reveals the type of the variable, and the developer reading the code does not have to go through the mental friction of inferring from the name or from how it is being used in the context or traversing back to where the variable was defined.

For weakly typed languages like JS/Python it has the huge additional benefit of making debugging that much easier, when one treats the prefix as the intent of what should be the value stored it reveals possible issues immediately when steping through code.

When the end goal is the benefit to 'other' developers reading your code Systems Hungarian makes perfect sense. Yes, it does mean some time getting used to it, but it's no different then any other coding pattern you habituate yourself to.

We end up gravitating towards the familiar and find other patterns ugly which in my opinion is the root cause of the negativity against type prefixing.

JavaScript and Apex variable prefixing

Variables are prefixed using letters from primitive types, the base 'Object', or `f` for functions. An exception are arrays that are prefixed with `a` even though the base type is an Object - this keeps the rule list small and as follows:

// Note: you can use `` to get the primitive type of it. 

var nYear; // for Numbers 
var bGender; // for Booleans
var sName; // strings
var oTable; // objects
var aScores; // arrays
var fAge = function () {}; //gets age of the person

I am was happy to find at one other person thinks the same: what-do-you-mean-by-the-initial-letter-on-javascript-variables-functions.

Apex variable prefixing

Blob blBlobieFoo; 
Boolean bBooleano;
Datetime dtStartDateAndTime;
Decimal dAgeOfUniverise;
Double dbBiggerNumber;
Integer iUserAge;
Long lTurlleAge;
Object oContentList;
Object oContentMap;
String sFirstName;
Time tAlarm;

// Methods??? m??? mUserAge // unsure about this one, thoughts?

What are you thoughts on this?

No comments:

Post a Comment