Staying DRY
One of the first things we learnt at university was to scan through our code at intervals to see if several parts share similarities and factor out the shared aspects into its own container of reusable code. This follows the DRY principle (i.e.'don't repeat yourself') and is a key principle any software developer must understand:
When you are building a large software project, you will usually be overwhelmed by the overall complexity.Just like the idea of recursion, as you divide systems into components, and, further, components into subcomponents, you will arrive at a level, where the complexity is reduced to a single responsibility.
You only want each 'piece' of knowledge to appear exactly once in your project/system.
But why? Well one obvious reason is because it saves you from typing out often quite complex logic over and over again throughout your code. It also lessens the chance of you making a mistake somewhere in one of those repetitions. But arguably most importantly, it means that if you want to come back later and make a change to the logic, you only have to update it in one spot!
Decorator Functions
These are functions that augment objects with additional properties and functionalities. To illustrate, let's take the example of a vehicle. There are many different types of vehicles, with some features common to all vehicles, some features common to a few vehicles, and then some features that belong only to one type.
function vehicle (vehicleType) {
this.vehicleType = vehicleType || car;
this.model = 'default';
this.license = '000-000';
}
var truck = new vehicle('truck');
// Truck now has a type, a model, and a license number.
// Let's now 'decorate' the truck with some decorator functions:
truck.setModel = function (modelName) {
this.model = modelName;
}
truck.setColour = function (colour) {
this.colour = colour;
}
Functional Classes
While a decorator function serves to add onto an object's functions/properties by accepting the target object as input, a class actually builds the object's along with the characteristics it is augmenting. A class is a template definition of an object's properties and methods.
Here is the difference in a simple example:
// Decorator Function
var fruity = function (fruit, colour) {
fruit.colour = colour;
return fruit;
};
// Class - note the naming convention is a capitalised noun
var Fruit = function (colour) {
var fruit = {colour: colour, pieces:1 };
return fruit;
};
The Fruit function is referred to as a constructor function, where the fruit returned will be a instance of the class.
A call to the constructor function, i.e.
var banana = Fruit("yellow");
is referred to as 'instantiating'.
Because functions are just objects and can store properties, you can add in any shared methods simply using dot notation:
Fruit.methods = {
slice: function() { this.pieces*2; }
};