Design Patterns – Is Singleton pattern evil?

To hell with everything. Why the hell use singleton or even why the hell it is described as a pattern by GOF?

I don’t know. I have been reading, studying and even trying to code and use the same design patterns in real life. The very first and easy to understand pattern is Singleton. This pattern was defined/recognised/identified as a pattern which assures creation of one and only object throughout the life cycle of a program. Common or say classic example given is error logging mechanism. And that’s the only real world example. Rest of the examples such as file or database handles are not suitable examples. They can be said as good example but not perfect.

Why singleton is evil?

I don’t want to reinvent wheel. There are n number of reasons. The reason I found is, tight coupling. Coupling in OOPS or even Software Development is discouraged. Loosely coupled systems allow more robust testing. You can replace the modules with dummy modules, equivalent modules and test the system. In this scenario a file logging mechanism is a perfect example of singleton pattern. The mechanism can be file logger, database logger or any other logger and will not affect our system if we replace it. Coz its not tightly coupled to system. Or as I read some where it simply “gets” the information and doesn’t “set” anything in our system. On the other side a database layer can’t be singleton pattern. What if I replace my MySQL layer with PGSQL? The system may not perform as expected or worst may break.

I suggest using singleton pattern shamelessly if your system is going to be a very tightly coupled and is custom and specific to a requirement. My argument is performance counts more than portability. Ofcourse Bullet 350 is no match to Splendor and Splendor is no match to Bullet 350. So, singletons are evil but so is fire, if you use it to burn your neighbour’s house. Use fire to light up. Use singleton wisely. 🙂

Interfaces versus Abstract classes in PHP

Interfaces and abstract classes are similar because neither one can be used directly to instantiate an object. The key difference is that an abstract class can have some fully implemented methods, whereas interfaces just have method declarations. Use abstract classes when you want to maintain the same methods in all your subclasses but have some general functionality that can be shared by the subclasses. Use interfaces when the implementations will differ across most or all the methods in subclasses.

Edited on 12th December @ 13:00 Hrs
More differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

  • Neither Abstract classes or Interface can be instantiated.

Edited (again :-/ ) on 16th Dec @ 16:40 Hours IST

When to use what?

  • Use Abstract class for creating a bond between similar items like Splendor and Bullet 350 are similar entities, motor bikes, so extend them from abstract class like Bike.
  • Use interface for creating a bond between dissimilar items like Splendor and Civic are different from Bike but both are vehicles, have engine, have mileage, have wheels, consume fuel, and so many common behaviors.
  • Always try to use Abstract class or interface whenever you need to up-cast them to achieve simplicity e.g. accelerate and brake methods of bikes.

(not so) Short and (but still) sweet. 🙂

A small introduction to Object Oriented JavaScript

Lately I have been studying Object Oriented Programming. I come from a background of small snippets, everything wrapped inside a small bulletproof function. Optimized to run as fast as possible. Things have changed from simple print function to more sophisticated print method or a system class (arghh!!!).
When I first wrote a piece of code for Linux I was told, everything is a file on a *nix system. So even if it is a directory/socket/drive/device you can treat it as a file and open it, read from it and write into it. So if you are going to do anything related to Linux tell yourself, everything is a file. Same in OOPS, tell your self everything is an object and it has some properties and some methods or in general have members. No functions. No variables. Everything is inherited or abstract or private or protected or…
JS, abbrevation for JavaScript, is an Object Based language totaly different from C, C++, Java or .NET and it is not truly Object Oriented. But still there are tweaks and hacks that allows one to model some concepts of OO. Object Based languages are also reffered as Prototype based languages. Prototypes as the word implies are not concrete objects and hence do not possess all the qualities, read methods and properties, of an object. Hence a string object in JavaScript may be or may not be same as string object in any other language.
All said and done. What all OO features can be implemented using JS?
a) we can define our own Objects.
b) we can extend predefined objects
c) we can inherit objects, really?? “Yes Sire”.
d) we can simulate classes, remember simulation is far away from reality.
Time to jump into code. Do it yourself.

/*
Just a quick hack ;-)
*/
function d(str){
	document.write(str);
}

{//Brace added just to limit everything in to local scope
/*
a constructor
*/
var bikeSimple = function(){ }
/*
Or
*/
function simpleBike(){ }

var pulsor = new bikeSimple;
var splendor = new simpleBike();

}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
Initialise an object
*/
/*
a constructor
*/
var bikeSimple = function(modelName, cc, mileage){
	/*
	Private members.
	*/
	var modelName = modelName;
	var cc = cc;
	var mileage = mileage;
	function canBeDriven(){
		return true;
	}
	/*
	Public members
	*/
	this.color = 'Black';
	/*
	*/
	this.sounds = function(){
		d('Vroom!');
	}
}
var pulsor = new bikeSimple('Pulsor DTSi', '150/180/220', '40-50');
/*
Or even the Object Initializer way.
*/
var cruiserBike = {modelName:'Bullet 350', cc:'350', mileage:'45-50' }
}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
Set/Get/Delete properties using methods
*/
/*
a constructor
*/
var bike = function(){
	this.setInfo = function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	}
	this.getInfo = function(){
		d('Model: ' + this.modelName + 'CC: ' + this.cc + 'Mileage:' + this.mileage );
	}
	this.vroomProperty = 'vroom!!!';
	this.vroom = function(nTimes){
		nTimes = (nTimes < 0 ? 1 : nTimes);
		for(i=0;i
			d(this.modelName + ' says ' +this.vroomProperty);
		}
	}
}
/*
Sample (and simple too!) invocation
*/
var pulsor = new bike;
pulsor.setInfo('Pulsor DTSi', '150/180/220', '40-50');
pulsor.getInfo();
pulsor.vroom(5);
/*
Or even this also works, not the OO way to do things
*/
function cruiserBike(modelName, cc, mileage){
	this.setInfo = function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	}
}
var bullet = new cruiserBike;
bullet.setInfo('Bullet 350+', '350', '40-45');
bullet.getInfo = function(){
		d('Model: ' + this.modelName + 'CC: ' + this.cc + 'Mileage:' + this.mileage);
	}
bullet.getInfo();
/*
But wait...
*/
var thunderbird = new cruiserBike;
thunderbird.setInfo('Thunderbird', '350', '40-45');
/*
This will throw an error
thunderbird.getInfo();
*/
/*
That vroom property is stupid, delete the property.
*/
delete pulsor.vroomProperty;
pulsor.vroom(5);
/*
Can I do this?
Apparently not this way.
*/
delete pulsor.vroom();
pulsor.vroom(3);

/*
...but this way, look no parenthesis
*/
delete pulsor.vroom;
pulsor.vroom(3);

/*
And the Object Initializer way. This led to JSON.
*/
var ducatiMatrix = {setInfo: function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	},
	getInfo:function(){
			d('Model: ' + this.modelName + 'CC: ' + this.cc + 'Mileage:' + this.mileage);
		}
	}
ducatiMatrix.getInfo();
}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
The power of prototyping
*/
/*
a constructor
*/
var bike = function(){}
bike.prototype.setInfo = function(modelName, cc, mileage){
	this.modelName = modelName;
	this.cc = cc;
	this.mileage = mileage;
}
bike.prototype.getInfo = function(){
	d('Model: ' + this.modelName + 'CC: ' + this.cc + 'Mileage:' + this.mileage );
}
/*
Sample (and simple too!) invocation, again!
*/
var pulsor = new bike;
pulsor.setInfo('Pulsor DTSi', '150/180/220', '40-50');
pulsor.getInfo();
/*
...& the following
*/
Date.prototype.myBirthDay = function(){
	return('My birthday falls on 3rd December, you can gift me iPods, Zunes, Toughbook, high speed data line..');
}
/*
Chainining the object, and look the Date is a native object and I haveadded my own method to it!
*/
d((new Date).myBirthDay());
}//Brace added just to limit everything in to local scope
 

Forcing browser to show file download prompt for html file – The Content-Disposition Header Field

I came across an interesting post title how to use PHP/Perl to display JavaScript. Interesting in the sense that author have displayed a nice way to dump JavaScript. I have another way of doing the same. I will simply save a JS file as a PHP file and will add some header statements on top of it and will use this PHP file as a JS source file wherever I want. This way I can take advantage of environment variable or some other setting. Its not rocket science. But header can do a lot. Look at the following example.

  <?php
$examplFiles = array(
array('name'=>'an-html-doc.html', 'mimeType'=>'text/html', 'disposition'=>'inline'),
array('name'=>'an-html-doc.html', 'mimeType'=>'text/html', 'disposition'=>'attachment'),
);
$id = $_GET['id'];
if(isset($examplFiles[$id]) && file_exists($examplFiles[$id]['name'])){
header('Content-Type: '.$examplFiles[$id]['mimeType']);
header('Content-Disposition: '.$examplFiles[$id]['disposition'].'; filename='.$examplFiles[$id]['name']);
ob_clean();
flush();
readfile($examplFiles[$id]['name']);
exit;
}else{
echo 'Error 404, file not found!';
}

Save this file on your LAMP stack with a name, say “a-cool-php-script.php” and access it through your browser with some id passed to it. Of course you also need to create an html file and named “an-html-doc.html” to run this script or all you will get is 404 error. For id=0 the html file will be displayed in browser and for 1 you will be presented with a file download dialog box or prompt.

Isn’t this interesting. You an use this simple code snippet to check any kind of file. All you need to know is MIME type of the file. A list of MIME types can be found here.

The example is in PHP but same will work for any web scripting language. For more read RFC 2183.