Archive

Archive for the ‘front end’ Category

why css still sucks for layout

June 11th, 2009 admin No comments

I’m really pissed off with the CSS fanboys let me tell you. Their devotion to CSS-P is so religious that their collective argument sounds annoyingly rhetorical at best.
Is there such thing as pragmatism?? I’m aware that pragmatism isn’t always the desired way to build software and systems. Heck, If I’m building a software to control nuclear reactors, I would be scared to let my pragmatism rule the software design, I can’t risk blowing a whole city or country and I’d have to take utmost care in every step I take to ensure I follow proper protocols and procedures so I don’t fry a city or entire country accidentally.

But lets face it, designing a website is not the same as designing a nuclear reactor control system.
And as such I can afford to say screw semantics, screw standards, screw them all if they screw up my time and resources and force me to think less of design and shitload more of hacks to just get things right.
I don’t care to get things just right. I want things to be damn right to start with. And if semantically incorrect methods permit me to do so, so be it.

I was just wondering, if HTML table was repackaged with absolutely no changes to any of its markup structure and behavior and called grid and renamed tr,td,th too, would all the CSS-P fanboys use it??

    <grid>
    <row>
   < unit> "Grid Glory"
   < /unit>
   < /row">
   < /grid>

To me its utter nonsense to not use a feature just because of semantic concerns and feeble arguments of SEO, accessibility etc.

The thing that really pisses me off though is the fact that as soon as someone raises concern about CSS/DIV based designs, all the CSS fanboys gang up and point their fingers and tell people that the reason they have problem with CSS/DIV based layout is because they are just plain ass dumb.

These bright new fanboys are pretty fanatic and everywhere I read, their arguments are just the same. Standard arguments, boxed arguments.

And they talk about the amount of code in the markup that makes table-based layout horrible to maintain not to mention the bandwidth penalty.

As if the amount of css hack that has to be conjured to do simple layouts doesn’t need maintenance and as if it loads by magic on the browser and bandwidth issue becomes non-issue….

CSS /DIV based layout is counter-intuitive to say the least. Who starts thinking in terms of float and clear when designing anyway??
If I want to add a new element to the a layout, I not only have to think about the size of the element but I have to make damn sure that the rest of the page doesn’t break by a mere addition of an element in a page. Which forces me to look at the whole design in terms of pixels, margins and paddings to add be able to add
a new element to a layout item. And that doesn’t prevent content/elements bleeding off the layout container.

And how about overlap problems??
I can break the best laid out CSS site by merely adding one more element to it……

CSS has merely opened a new job market and allowed people to make loads of money out of it. And the fanboys of CSS/DIV layout guard their self-interest with great zealot because without CSS they will be out of jobs. I mean, who’s going to write a page full of CSS hack to give us merely a 3-column fluid layout with column-size constraints. And then they write one more page full of CSS hacks to prevent the content from bleeding out of their containers, with partial success.

Web-development has taken a great leap backward as a result of the push to use CSS/DIV/SPAN for layouts.
Because we spend most of the time not in designing pages but in applying hacks to make them look devent on most browsers.

If the fanboys close their eyes for one minute and forget everything bad that had been hammered into their head about tables and think of it as a grid, u’ll be damn surprised how intuitive it is to design in terms of grids. All decent desktop GUI toolkit provide grid-based layout which allows us to apply constraint to layout grid-elements in relation to other grid elements and so on.

Why?

The fanboys might argue that the GUI toolkit designers were mere dumb people who still hold on to the grid-based layout of last century and blah blab and some more blah.

And when the fanboys run out of ammunition, they fallback to blaming browsers and declare its the fault of browsers and nothing else.
And meanwhile they bleed to death trying to make a simple layout work in most browsers with tons of css hacks which still doesn’t quite do the job. why?

CSS is ill-equipped to handle layouts…..The language or pseudo-language of CSS was designed by people who have no knack for Designs, if they did, the language would have been more intuitive than this terrible piece of work. I come from a programming background and I love beautiful designs and I like to pretend I can create cool designs and sites. For me CSS/DIV layout makes no sense from either a programmer’s prespective or a designer’s.

From a programmer’s perspective I like parameter driven development to simplify things, and from a designers perspective, I’d hate to have to hand-code the whole friggin page design and have to come up with countless hacks to overcome both CSS and browser shortcomings.

CSS sucks so bad that even though billions of people use the internet everyday, yet no decent visual designing tool has come out so far. The one decent WYSWYG editor Dreamweaver fails miserably when designing layouts in CSS.
Where’s the forward mobility promised by this new technology??

Categories: css, front end Tags: ,

Javascript variable scope, private protected and public

May 27th, 2009 admin 2 comments

Javascript is a tricky language. Since I learned programming with Java, I always find myself trying to find its equivalence in other languages I come across.

I know its bad in that in that it kind of stops me from exploring the potentials provided by other languages in full. Its like going to a Chinese restaurant and eating fried rice everytime because fried rice is the only dish that is close to what I’m used to eating daily.
There’s such variety in Chinese food, and yet if I go there and I eat fried-rice evertyime Its a sign I have a bit of a problem opening myself up to new things. And that’s a big problem.

The world has such diversity in every-aspect imaginable, ( with the exception of mob-justice and mob-mentality which seem to cross all cultural and geographical boundary as it seems), and not being able to appreciate the diversity and learn for it is a great pity.

Back to programming, not all constructs  found in languages are sole property of a  given language. They are  generally abstractions provided by languages to solve problems effectively and those abstractions can be applied in other languages even if they don’t provide such explicit constructs.

There was a time when I treated javascript like lepers, something to avoid at all cost, except when it was really unavoidable.
But then I had a change of perspective, at a philosophical level -dare I day. ‘If I avoid something to such length then I must be shit-scared of it for some reason’.
And by nature I hate to admit my fears for the fear of being tagged a wussy, a chicken.
Of course I can find things to justify my avoidance of javascript to others without admitting my fear, but how about myself?
What do I tell myself when I go to sleep??
And since I couldn’t find reasonable arguments to fool myself into good sleep because my rational self always counter-argued that ‘you  fear what you don’t understand’, and my arguments against javascript were just my lame attempt to hide my fears , I decided to deal with my fears for once and for good.

And since then I have been quite happy with my javascript experience.

Since I’m still a Java fan-boy, though I have a feeling that it won’t be for  too long, Scala! here I come,  I tried to find solution to variable scoping in javascript so that I have more control over objects I create and the API’s I expose. This has been a big issue due to the need for me to use at least 3-4 third-party libraries to get my job done for the current project I’m rewriting.
And the project has a massive javascript code-base.

Looking back at the code I did last year makes me cringe. There was no modularity and there was too much interdependency between components and objects.

(Hmm… component decoupling is entirely another topic for another sleepless night.)

And this time around I decided to do thing the right way – at least to my best knowledge.

After long hours prowling the internet, finally I managed to understand the trick to accomplish what I wanted.

So here’s an example of an object with everything pubic, the dumbest example.


var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;

this.getFullName=function(){

return this.surname+","+this.name;
}

this.getAge=function(){

return (new Date().getYear() - this.dob.getYear()) ) ;// I'm being lazy here

}

}

// another a little less dumb-looking flavor with prototyping but dumb nonetheless
var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;
}

Person.prototype.getFullName=function(){
return this.surname+","+this.name;
}
Person.prototype.getAge=function(){
return (new Date().getYear() - this.dob.getYear()) ) ;
}

All the properties in of the object are accessible to any function/code that instantiates Person object. And getFullName() is nothing more but a handy method for getting both name and surname.
And the calling code can access dob and compute age by itself.
So everything is accessible.

var person = new Person('inny', 'minny', 'yes please', new Date(1901, 0, 1) );

var fullname= person.surname+","+person.name;

var age=  (new Date().getYear() - person .dob.getYear()) ) ;

Of course one can argue that we can differentiate the difference between private and public by using underscore for private properties such as _dob ( as a lot of people insist on doing).

But who are we fooling? That’s just a convention we use, and if you work in a large team there’s no guarantee that someone else will not get smart and start mutating the underscored variable and shit might hit the fan depending on how critical the property is.

Instead of developing ad-hoc convention I believe its more ideal to use the best of what a language provides without having to define our own rule which can be broken by anyone who cares to break it. Sometimes I don’t trust myself,let alone trust others.

So if we need to hide the DOB for privacy reason and only expose the age,  and we need to hide the individual name and surname for some reason, here’s how its done:

var Person= function(name ,surname, sex, dob){

this.sex=sex;

this.getFullName=function(){

return surname+","+name;
}

this.getAge=function(){

return  (new Date().getYear() - .dob.getYear()) ) ;

}
}
Person.prototype.getGender=function(){
var sex=this.sex,tolowerCase();
if( sex=='male' || sex=='m' )
return 'male';
else if( sex=='female' || sex=='f' )
rerturn 'female';
else
return 'god knows';

}

Person.prototype.getSpecies=function(){

return 'mammal';
}

In the above example, any instantiating code has only access to getFullName() , getAge() functions and ’sex’ variable of person object.
But we allow ’sex’ variable to be declared in two forms, long and short. And we return ’sex’ in  long format with the help o getGender() helper function.

The above example can be broken down as following;

All variables except sex are private as they are constructor-scoped.
getFullName() and getAge() are privilaged function that have access to private variables name, surname and sex and thus are privileged/protected functions.

getGender() is a public function that has access to public variable sex.
the new getSpecies() is a public function that returns a value that’s entirely in its own scope.

So, there we have it, private, privileged and public access in javascript.

If we want to use module pattern the above can be modified to:

var Person= function(name ,surname, sex, dob){

this.sex=sex;
return{

getFullName:function(){

return surname+","+name;
},

getAge:function(){

return  (new Date().getYear() - this.dob.getYear()) ) ;

},
getSpecies:function(){

return 'mammal';
}

}
}

An example of creating static object with private and public scope:

var Human = function() {

var species = "mammal";

return {

alert: function(){alert(species);}

};
}();

Human.alert();//displays 'mammal'

Here the variable species is private.
The function gets executed immediately due to () at the end of the function definition and will return a public static method alert()

That sums up variable scopes in javascript.

using java style import to include javascript files

May 23rd, 2009 admin No comments

I had used a function and a little bootstrapping trick to solve my problem with including files in PHP and I was happy with it.
But recently while working on a project that has a heavy javascript codebase, I started having trouble managing  all javascript file imports and all those script tags made pages look really ugly.
And also I really longed for java’s clas importing capabilities in javascript such that I could import a single file based on package name or I could import a whole package.
Since some of the pages I’m working requires over 15 script imports, some third-party libraries and some of our own files.
And importing scripts one by one suffers from latency problems as it increases page load time and can contribute to user annoyances.
So I longed for  java’s style of package and class  import and  decided to try my hand on writing some script to emulate imports based on packages.

I jsut used the  similar principle I used with php, but the problem is importing all files in a package isn’t possible in javascript because  javascript cannot read files form disk let alone iterate through a folder and read file content.
For that there was nothing I could do except use some server-side help.

here’s the js file code with  function for importing js file and js files contained in a package(folder).


//create namespace to aviod any present/ future  variable/object/funciton conflicts

if (typeof Anzaan == "undefined" || !Anzaan) {

Anzaan = {};
}

// array to hold all imported files so as not to import them twice
Anzaan.imports = [];

//server side URL for loading whole package content
Anzaan.packageLoaderURL='/Framework/packageLoader/';

//set the base folder for importing files
Anzaan.importBase='js/';

/**
* import a class using the java naming syntax for a class name.
*@param module the module to import
*@param  config object literal with two properties-
* config.packageLoaderURL - the server url for loading all files in a folder/package as a stream
* config.importBase - the base path for importing files
* use config only if necessary otherwise just modify Anzaan.packageLoaderURL and Anzaan.importBase
* of course you can use a different namespace or just use no namespace
*/
function Import(module, config) { //com.anzaan.framework.*

if(config){
if(config.packageLoaderURL)
Anzaan.packageLoaderURL=config.packageLoaderURL;

if(config.importBase)
Anzaan.importBase=config.importBase;
}

// if this import has already happened, don't bother,
if (Anzaan.imports[module] )
return ;

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';

var src='';
var folders=module.split(".");
for(var i=0;i<folders.length;i++){

if(folders[i].indexOf('*') < 0)
src+=folders[i]+"/";
}
src=src.substring(0,src.length-1);//remove the last slash

if (module.indexOf('*') < 0) { //if not package import
src=Anzaan.importBase+src+".js";
script.src=src;

} else {
script.src=Anzaan.packageLoaderURL+"?package="+Anzaan.importBase+src;
}

head.appendChild(script);
Anzaan.imports[module] = module;
}

The config parameter is optional. It shouldn’t really be used unless you want to load files from locations other tahn the default location of your application and want to use other URL for loading script files.

Just modify the global variables Anzaan.packageLoaderURL and Anzaan.importBase to set the base path and the serverside URL for loading scripts in folder.
And of course rename Anzaan to something more meaningful for you.

Now on the server side here’s a simple php script that services the script file requests.
It loads contents from js flies that reside in folder specified by ‘package’  variable.

packageLoader.php
————————————————

<?php

$folder=$_GET["package"]; // get the package name

$dir = opendir($folder); //open directory

while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.js')) {

echo file_get_contents($folder.'/'.$file); //printout the content of file

}
}

?>

and here’s a Java Servlet for doing the same thing:

JSPackageLoaderServlet.java

public class JSPackageLoaderServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/plain");
ServletOutputStream out = response.getOutputStream();

String packagePath = request.getParameter("package");

StringBuilder sb = new StringBuilder();

File myDir = new File(getServletContext().getRealPath(packagePath));
if (myDir.exists() && myDir.isDirectory()) {
File[] files = myDir.listFiles();
for (int y = 0; y < files.length; y++) {

String line = "";
BufferedReader in = new BufferedReader(new FileReader(files[y]));

while ((line = in.readLine()) != null) {
sb.append(line);

}

}

}
out.print(sb.toString());
}
}

Here’s the usage:

Import('anzaan.event.EvenHandler');