How to write code that is simple and easy to manage
One question I get asked by programmers that comes from other languages are:
How to make private variables and methods in JavaScript ?
You do it by using an anoymous function that calls itself ...
var globalObject; (function() { globalObject = {}; var privateVariable = "bar"; function privateFunction() {} globalObject.publicMethod = function() { return privateVariable; } })(); // call itself
How are private variables useful
When you feel the need to have private variables and methods, you are writing complex code: Code that entangles other code and makes the code-base more complicated and slower to maintain for each iteration.
But sometimes it is just inevitable, like when making abstractions or gluing two components together, calling it an API.
Lets say you are making a engine "module" to be used in a car, but just want to expose a throttle method and a speed gauge, and not all the functions and variables the engine use internally.
It basically just hides complexity in a box that makes it easier to reason about. And you can be sure that only the global/public variables entangles with the outside, making your code less bad.
How to avoid complex code
It's very hard to not have code that doesn't interact with other parts, or modules.
But if your code needs to interact with something, make it interact with only one thing!
In the car engine example, the engine should be a plugin, not a module. And the car should provide an API that the engine can be "plugged in" to.
Whatever you do, do not let modules interact with each other! Then it's not a module, just a masqueraded global, that you need to know about.
It's OK to have other modules as dependencies, like a tree. But not as in a spaghetti.
Written by Johan Zetterberg Mars 2nd, 2016.