Think about the right box, it should be the state of the current Web 2.0 Era ... now think who is in charge to maintain the layer between your server application, and the customer ... I am quite sure 90% of cases will be a Web Designer, rather than a Senior skilled JavaScript Developer ... now wonder why if you ask for JavaScript skills plus Photoshop, you will rarely being able to make right profits from your business. JavaScript is not a toy, and "web speaking", is one of the most important programming language your team should know, it's time to stop to underestimate it.
behind the design
My JavaScript book is out!
Don't miss the opportunity to upgrade your beginner or average dev skills.
Showing posts with label design. Show all posts
Showing posts with label design. Show all posts
Saturday, April 25, 2009
JavaScript Is A Toy? So C#, Java, PHP, and Python Are!
I wrote a truly big post about this subject ... but it was nervous and not that technical as well. I decided then to simply post this image, hosted in Pam webOS Project page:

Think about the right box, it should be the state of the current Web 2.0 Era ... now think who is in charge to maintain the layer between your server application, and the customer ... I am quite sure 90% of cases will be a Web Designer, rather than a Senior skilled JavaScript Developer ... now wonder why if you ask for JavaScript skills plus Photoshop, you will rarely being able to make right profits from your business. JavaScript is not a toy, and "web speaking", is one of the most important programming language your team should know, it's time to stop to underestimate it.
Think about the right box, it should be the state of the current Web 2.0 Era ... now think who is in charge to maintain the layer between your server application, and the customer ... I am quite sure 90% of cases will be a Web Designer, rather than a Senior skilled JavaScript Developer ... now wonder why if you ask for JavaScript skills plus Photoshop, you will rarely being able to make right profits from your business. JavaScript is not a toy, and "web speaking", is one of the most important programming language your team should know, it's time to stop to underestimate it.
Thursday, June 19, 2008
A completely revisited Singleton and Factory design pattern for PHP and JavaScript
Singleton
From Wikipedia
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern by some people, who feel that it is often used as a euphemism for global variable
Basically, the last point is true.
Whatever we think about Singleton, we cannot say that we do not use this pattern to have the same instance, or object, in every place of our application.
The most common case scenario, is usually a database object, or a global queue, used as a stack, or something similar, like a template engine instance or a DOM / XML node.
The worst thing ever, is that with languages like PHP and JavaScript, the Singleton pattern is really hard to implement correctly.
Why bother with a class?
In a lot of frameworks, as in a lot of libraries, I have seen every kind of Singleton implementation, and most of them, are conceptually hilarious.
// PHP Singleton classic example
Singleton::load('MyCLassName');
MyClassName::getInstance();
// JavaSript classic example
MyConstructor.getInstance();
// where in different cases, getInstance
// is not even defined inside a closure
// to preserve singleton integrity ...
// ... but does exist a way to make
// a JS constructor private? NO
With PHP, problems are different:
- if there's no magic __clone method, it does not make sense
- if you serialize and unserialize objects, it could not make sense
- if you create a Singleton class, it is nearly impossible to extend correctly its behaviour (come on lazy binds and PHP 5.3!!!)
- if you try to create a __callStatic method, you simply have to wait next PHP release
In PHP again, as is for JavaScript, outside a closure, every static function is global.
This means that we do not need to use global something, in PHP, and we do not use, usually, window as prefix to use declared function.
It is true, the most horrible piece of code you can spot in an entire PHP application, is the usage of global keyword to transport variables everywhere.
We do not need that, and we can have a Singleton behaviour, simply using a function !!!
function Singleton($__CLASS__){
// webreflection.blogspot.com
static $list = array();
if(!isset($list[$__CLASS__])){
$arguments = func_get_args();
array_shift($arguments);
$instance = new ReflectionClass($__CLASS__);
$list[$__CLASS__] = $instance->getConstructor() ? $instance->newInstanceArgs($arguments) : $instance->newInstance();
}
return $list[$__CLASS__];
}
Is static variable private inside function scope? Yes
Is this function smarter than a public static method? Yes
class A {
protected $value = '123';
function write($what){
echo $what.$this->value;
return $this;
}
}
class B extends A {
function __construct($value){
$this->value = $value;
}
}
echo '', var_dump(Singleton('A') === Singleton('A')), '';
echo '', var_dump(';
Singleton('B', 'my value')->write('Hello World') === Singleton('B')
), '
// true, Hello Worldmy value, true
Do you really want a class?
Ok, somebody could thing that above function is pointless, so here there is a class that will use the same function.
class Singleton {
// webreflection.blogspot.com
private $_class,
$_instance;
public function __construct($__CLASS__){
$arguments = func_get_args();
$this->_class = new ReflectionClass($this->_instance = call_user_func_array('Singleton', $arguments));
}
public function __get($property){
return $this->_instance->$property;
}
public function __call($method, array $arguments){
return $this->_class->getMethod($method)->invokeArgs($this->_instance, $arguments);
}
public function __set($property, $value){
$this->_instance->$property = $value;
}
public function equal($_instance){
return $_instance instanceof Singleton ? $this->_instance === $_instance->_instance : $this->_instance === $_instance;
}
}
With above class, using the Singleton function as well, you can even use the new keyword to obtain every time the same instance.
$b = new Singleton('B', 'my value');
echo '', var_dump(';
$b->equal(Singleton('B')->write('Hello World')) &&
$b->equal(new Singleton('B'))
), '
Well, at this point we have the shortest way to obtain the same behaviour, using, or not, a class.
Factory
From Wikipedia
The Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.
The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.
Specially in PHP, a Factory pattern is useful to avoid problems with new keyword when you create an object.
For example, this is not possible:
new Class("stuff")->doStuff();
With a Factory behaviour it is natural to do something like this:
Factory('Class')->doStuff();
In those case when we need an instance once, or few times, and never more, to do some super cool computation, we could avoid variable assignment and, in some case, use a function with the same class name as proposed few days ago.
But this time, using exactly the same concept of Singleton, it is even more simple to create a general purpose Factory function:
function Factory($__CLASS__){
// webreflection.blogspot.com
static $list = array();
if(!isset($list[$__CLASS__]))
$list[$__CLASS__] = new ReflectionClass($__CLASS__);
$arguments = func_get_args();
array_shift($arguments);
return $list[$__CLASS__]->getConstructor() ? $list[$__CLASS__]->newInstanceArgs($arguments) : $list[$__CLASS__]->newInstance();
}
Some example?
class A {
public function setName($name){
$this->name = $name;
return $this;
}
}
$me = Factory('A')->setName('Andrea');
echo $me->name; // Andrea
Not every consideration I did for Singleton pattern is true for Factory one, but the structure of the function, as the possible class, is about the same.
At this point, assuming that in my implementation Factory is an extended version of the Singleton, creating more instances than one, you can have a look into the complete source of my Factory and Singleton implementation.
Why there is JavaScript in this post topic?
The reaon is simple, everything I have done with PHP, is simply replicable with JavaScript, but this time, with only 8 lines of code:
// webreflection.blogspot.com
Factory = function(__CLASS__){
for(var i = 1, length = arguments.length, args = new Array(length - 1); i < length; i++)
args[i - 1] = "arguments[" + i + "]";
return Function("return new " + __CLASS__ + "(" + args.join(",") + ")").apply(null, arguments);
};
Singleton = function(list){return function(__CLASS__){
return __CLASS__ in list ? list[__CLASS__] : list[__CLASS__] = Factory.apply(null, arguments);
}}({});
Seems to be simple, isn't it? :geek:
Sunday, June 01, 2008
PHP or JavaScript implicit Factory method design pattern
Update
Above technique could be used to create an implicit Singleton as well.
I have talked about JavaScript possibility different times in my prototypal inheritance documentation, and in other posts of this blog. The summary is that thanks to perfect this behaviour, that for some unknown reason someone would like to modify in JS2, making them ambiguous when you are using a constructor as a function and not, for example, as private method, we can create intelligent constructors that does not require the usage of new keyword - in a Pythonic way:
The main advantage, using this technique, is that we write less code and we are able to concatenate every public method, allowing us to do different stuff in few lines.
We could use simply constructor when we would like to create an instance and use then directly a public method.
Above examples show JavaScript new keyword nature, and its priority when we use brackets around, or at the of the constructor - passing, or not, one or more arguments. With implicit factory method purpose, we could simply do stuff like this one:
To be honest, with native or defined constructors, we should put more effort to implement my proposed technique, but the aim of this post is to show how could be possibile to do the same, with PHP.
I suppose that if you are an Object Oriented PHP Programmer, you have tried, at least once, to do something like this and without success:
Since in PHP both usage of brackets and syntax are different, the "only" way we have to concatenate public methods is to create a manual factory one:
Above example is a very common one in many OO frameworks or libraries.
You probably don't know that thanks to some intrinsic PHP language ambiguity, it is possible to create a function with the same name of a class, as is, for example, for constants, but this time without future features problems.
The PHP interpreter is able to recognize if we are calling the class or the function, simply looking at new keyword.
If we are using them, it will be obviously an instance creation, while if we are not using them, it will be obviously a function call.
The last case is if we do not use brackets, and then it will be the defined constant, if any, or, in a better future, the static public __toString method, if any again.
Since this way to code and use classes and functions could be truly interesting, and since we could have one to thousands of classes, it is natural to think how to automatically implement this kind of feature in our project.
The answer is a function, called __autofactory, that will be able to create a file to include, or require, that will contain every defined class as function, using best practices to speed up implicit factory method usage.
The only thing to write before logic code execution, is this piece of code:
The first parameter will be the name of the file that will contain informations, while the second one will specify, if present and with a false evaluable data, if function should require them or not.
At this point, you have basis and / or code to use this particular feature for every kind of purpose.
Above technique could be used to create an implicit Singleton as well.
class Demo {
// your unbelievable stuff
}
function Demo($some, $arg){
static $instance;
return isset($instance) ? $instance : ($instance = new Demo($some, $arg));
}
Demo(1,2)->doStuff();
Demo(1,2) === Demo(1,2); // true
from Wikipedia
The factory method pattern is an object-oriented design pattern ... More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.
I have talked about JavaScript possibility different times in my prototypal inheritance documentation, and in other posts of this blog. The summary is that thanks to perfect this behaviour, that for some unknown reason someone would like to modify in JS2, making them ambiguous when you are using a constructor as a function and not, for example, as private method, we can create intelligent constructors that does not require the usage of new keyword - in a Pythonic way:
// JavaScript
function Person(name, age){
if(this instanceof Person){
this.name = name;
this.age = age;
} else
return new Person(name, age);
};
Person.prototype.getInfo = function(){
return this.name + " is " + this.age + " years old";
};
// Example
alert(
Person("Andrea", 30).getInfo() // Andrea is 30 years old
);
var a = Person("Luca", 25),
b = Person("Fabio", 31);
The main advantage, using this technique, is that we write less code and we are able to concatenate every public method, allowing us to do different stuff in few lines.
alert(
Person(name, age).transFormToEmployee(company).getInfo()
);
The new keyword
We could use simply constructor when we would like to create an instance and use then directly a public method.
var time = (new Date).getTime();
// same as
var time = new Date().getTime();
// different of
var time = new Date.getTime(); // Date.getTime is not a constructor !!
Above examples show JavaScript new keyword nature, and its priority when we use brackets around, or at the of the constructor - passing, or not, one or more arguments. With implicit factory method purpose, we could simply do stuff like this one:
// just a basic (and wrong) example of implicit factory implementation
Date = function(Date){
return function(){
return this instanceof Date ? this : new Date;
};
}(Date);
var time = Date().getTime();
To be honest, with native or defined constructors, we should put more effort to implement my proposed technique, but the aim of this post is to show how could be possibile to do the same, with PHP.
PHP implicit Factory method
I suppose that if you are an Object Oriented PHP Programmer, you have tried, at least once, to do something like this and without success:
echo new Person("Me", 30)->getInfo();
echo (new Person("Me", 30))->getInfo();
Since in PHP both usage of brackets and syntax are different, the "only" way we have to concatenate public methods is to create a manual factory one:
class Person {
// ... our stuff ...
static public function create($name, $age){
return new Person($name, $age);
}
}
echo Person::create($name, $age)->getInfo();
Above example is a very common one in many OO frameworks or libraries.
Ambiguity
You probably don't know that thanks to some intrinsic PHP language ambiguity, it is possible to create a function with the same name of a class, as is, for example, for constants, but this time without future features problems.
// PHP
class Person {
function Person($name, $age){
$this->name = $name;
$this->age = $age;
}
function getInfo(){
return "{$this->name} is {$this->age} years old";
}
}
// factory method!!!
function Person($name, $age){
return new Person($name, $age);
}
// Example
echo Person("Andrea", 30)->getInfo(); // Andrea is 30 years old
?>
The PHP interpreter is able to recognize if we are calling the class or the function, simply looking at new keyword.
If we are using them, it will be obviously an instance creation, while if we are not using them, it will be obviously a function call.
The last case is if we do not use brackets, and then it will be the defined constant, if any, or, in a better future, the static public __toString method, if any again.
The __autofactory function
Since this way to code and use classes and functions could be truly interesting, and since we could have one to thousands of classes, it is natural to think how to automatically implement this kind of feature in our project.
The answer is a function, called __autofactory, that will be able to create a file to include, or require, that will contain every defined class as function, using best practices to speed up implicit factory method usage.
The only thing to write before logic code execution, is this piece of code:
// ... application classes inclusions
// before code logic
require '__autofactory.php';
!file_exists($fileName = 'factory.function.php') && __autofactory($fileName);
The first parameter will be the name of the file that will contain informations, while the second one will specify, if present and with a false evaluable data, if function should require them or not.
At this point, you have basis and / or code to use this particular feature for every kind of purpose.
Subscribe to:
Posts (Atom)