Skip to main content

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 proponent of the Systems Hungarian notation, not the Apps Hungarian notation.

The merits become apparent when reading other people's code, or when you look at your own code months/years after. Properly naming variables can be hard, the type is not always obvious from the name itself 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 either the name, or from how it is being used in the context, or traversing 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 stepping through code.

When the end goal is the benefit to 'other' developers reading your code Systems Hungarian also 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 end up finding other patterns ugly, this in my opinion is the root cause of the negativity against type prefixing, or any naming conventions you don't use everyday. In the end I prefix because it has increased my own code readability to me.

Javascript Runtime Type Checking

Recently I have implemented a generic fObjectValuesCheck function which I now leverage during development to confirm correct values of Objects which are passed to and returned from functions, a damn time saver catching errors early on.

// from: https://stackoverflow.com/a/47074621
function fIsBoolean(n) {
 return !!n === n;
}
function fIsNumber(n) {
 return +n === n;
}
function fIsString(n) {
 return '' + n === n;
}
function fObjectValuesCheck(oObject) {
 for (let [sKey, oValue] of Object.entries(oObject)) {
  if (oValue !== null && sKey.match(/^n/) && fIsNumber(oValue) === false) {
   console.error('=== fObjectValuesCheck(', arguments, '): ERROR: non-number value detected in `oObject=', oObject, '`.');
   throw Error();
  }
  else if (oValue !== null && sKey.match(/^s/) && fIsString(oValue) === false) {
   console.error('=== fObjectValuesCheck(', arguments, '): ERROR: non-string value detected in `oObject=', oObject, '`.');
   throw Error();
  }
  else if (oValue !== null && sKey.match(/^b/) && fIsBoolean(oValue) === false) {
   console.error('=== fObjectValuesCheck(', arguments, '): ERROR: non-bollean value detected in `oObject=', oObject, '`.');
   throw Error();
  }
 }

}

// then in your main code you would write your functions as follow
function fSomeMethod(oArgs) {
 fObjectValuesCheck(oArgs); // will error out if passed `type` is incorrect
 
 let oReturn = {...}
 ...
 
 fObjectValuesCheck(oReturn); // will error out if returned value is of incorrect type
}

JavaScript and Apex variable prefixing

Variables are prefixed using letters from primitive/built-in types (Object.prototype.toString.call(variable)) and `f` for functions - this keeps the rule list logical and consistent:

// NOTE: use `Object.prototype.toString.call(variable)`

var nYear; // for Numbers (`[object Number]`)
var bGender; // for Booleans (`[object Boolean]`)
var sName; // strings (`[object String]`)
var oTable; // objects (`[object Object]`)
var mSKUMap; // objects (`[object Map]`)
var stColors; // objects (`[object Set]`)
var aScores; // for arrays (`[object Array]`)
var fAge = function () {}; //for functions (`[object Function]`)

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

Apex primitive types variable are prefixed as follows

Blob blBlobieFoo; 
Boolean bActionVisible;
Date daDateOnly
Datetime dtStartDateAndTime;
Decimal deAgeOfUniverise;
ID idUserRecord;
Double dBiggerNumber;
Integer iUserAge;
Long lTurlleAge;
Object oUserRecord;
Object oContentList;
Object oContentMap;
String sFirstName;
Time tAlarm;

mUserAge(...); // undecided on this one

What are you thoughts on this? But please no hating.

Comments

Popular posts from this blog

Duplicate value found: duplicates value on record with id: <unknown>.

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>. The above error is triggered in the database layer and caused by a trigger or workflow outside of your main code of block that is bubbling this exception. This is rather difficult to track down especially if you are unfamiliar with the code, I am sharing my procedure in the hopes this saves you time - if you find this helpful drop me a line or follow me on twitter @danielsokolows . This error is caused by unique field constraint on the object, so the first step is to examine the object and locate the API names of all unique fieds. You can do this through SF direclty 'Setup < Customize &lt <object being inserted> &lt Fields' or by downloading the `src/objects` metadata information and searching for <unique> ; I preffer the latter and actually download ALL matadata i

Softeher 'Error occurred. (Error code: 2)' sollution

Protocol error occurred. Error was returned from the destination server. The Softether server by default to run on port 443 , if you server also hosts normal https then 443 is already taken and so Softether can't bind to it. When you run `vpncmd` it attempts to connect, find an active port, but of course fails with 'Protocol error occurred. Error was returned from the destination server.' because it's not actually connecting to the vpn server. By default Softether also listens on 992 , 1194 , and 5555 so the sollution is to modify specify `localhost:5555` when executing the `vpncmnd`. If this has helped you feel free to comment or follow me on twitter @danielsokolows .

How to child proof a fireplace

DIY - Do it yourself fireplace child guard Our wonderful 8.5 month old Sofia has become a crawling race car with an untamed thirst for exploration. And so with the cold nights approaching we needed to child proof the fireplace. This however proved to be more difficult than would reasonably expect, I've checked the local Toys "R" Us, Walmart, and even a Canadian Tire with no success for a ready to use product. Internet search was more fruitful and returned a few online stores one could order from, however in all honestly they didn't look too sturdy to me. So I build my own relatively quickly and inexpensively. Materials needed is a privacy plastic lattice - the smallest hole pattern - a few screws and anchors; tools needed are a drill, and a handsaw if you don't have the lattice cut at the store - that’s it. The construction consits of screwing the lattice into the wall and the final product is easiest explained through following pictures.