Explaining Web to Hard Programmers

12 December 2011

I will use the term hard programmers here to describe people with background in server-side development and compiled languages like C++ and Java, who have never been involved in real web development. I first stumbled across this term when I was reading the book ppk on JavaScript.

Being surrounded by hard programmers myself, I found that describing all the specifics, processes and tendencies of web development to them is a challenging task. There are fundamental differences how traditional and web applications work. If you do not believe me, look at two questions that looks akward for web professionals, but are commonly asked by hard programmers:

  • When will HTML5 be ready?
  • Is it possible to use HTML5 and CSS3 when the browsers do not support it?

There are many variants of these questions, but basically, all of them regard the lack of features in browsers, something that web professionals know how to overcome. Hard programmers, however, do not face such a problem in other environments, where something either is working and can be used, or is not working and cannot be used at all.

So here are several points you should mention in front of hard programmers to explain how the Web works:

HTML5 and CSS3 are modular - each module has a separate life

What modular means in this case is that there are separate specifications for the different features and each of them is in different state (draft, recommendation, etc). Same goes for the implementations. While one feature may be very popular in mass media and thus implemented well even in early draft (2D Transformation being a good example), other may lack support in any browser today.

Having in mind the big competition between the browser vendors, waiting for all the specifications to become recommendations is not possible. Moreover, no one knows what "all the specifications" means. A new draft, for example, may be released tomorrow. This is an ongoing process. New features are continuously proposed. Not believing again? Look at css4 selectors, Fullscreen API, or the proposition about simplifying element creation.

This environment differs from Java SE, for example. When JDK 7 is released, you have all the features ready to be used. No partial implementations, no hacks to triggers a feature, no vendor prefixes.

Web apps do not need to behave the same in each platform

If this or this are not enough for you, here are some additional arguments in a form of examples:

  • The Google Docs application has an offline mode. Does it work in old browsers? No. Does Google care? No. The core functionality - to work online with documents, is always there. The offline mode is an enhancement for users that use modern browsers.
  • Twitter home page uses many CSS3 effects (shadows, rounded corners, opacity). Do these effects work in old browsers? No. Does Twitter care? No. The core functionality - to identify the brand and to log-in/register is always there. CSS3 is only an enhancement for users that use modern browsers.

Building applications with basic technologies while enhancing with features for advanced browsers is a tendency in web development which will never vanish. Hard programmers get to this paradigm very slow because there is no analogy with traditional application development, where everything should work the same in each platform.

Paul Boag has made a great document on how to explain the need of progressive enhancement to our clients. This might very well work for hard programmers too.

JavaScript is dynamic - it can implement features that lack support

An example that I really like because it shows the conceptional differences between JavaScript and other languages hard programmers are used to, is the following: in Java, you cannot use generics if you want to compile in Java 4. And you cannot define it. In JavaScript, you can implement generics in a browser that do not support it and still use it.

For a real example, localStorage can be implemented on top of other storage mechanisms that is available in the browser (IE userData, Flash Shared Object, Cookies...). And you will still use the localStorage API as if it is available in the browser.

For a concrete application, see diagram.ly, which relies on SVG, but also works in IE7.

HTML and CSS are not programming languages, but it helps to treat them as if they are

Although hard programmers are aware of the best practices to write source code, my observations on their markup and front-end code are discouraging. They copy-paste a lot of HTML, CSS and JavaScript handlers written directly in the markup and they don't have any clue that this code should also be organized or that some principles should be followed.

If you are a web professional who has to work with hard programmers, explain to them that HTML and CSS are also source code and make them think about these technologies as programming languages. That may help to trigger some sense to follow best practices.

Final Note

I recently helped my colleague Plamen Todorov to create this excellent presentation about why should we care about html5, css3 and JavaScript. Since Plamen is more concentrated on JavaScript, there are less arguments and links for html5 and css3, but still it's a very strong research regarding the latest tendencies.

The Next Five Years Will Be Very Exciting

26 September 2011

In May 2010, the (now former) Google employee Brad Neuberg gave an amazing presentation about the new and emerging technologies in web development. The name of the topic is HTML5 and the Future of the Web, but don't let this title fool you - it's not dedicated only to HTML5 but also to CSS3, SVG and the new JavaScript APIs. According to Brad:

HTML5 = Next Generation Features for Modern Web Development

Fortunately, a high quality video is uploaded on youtube. Although May 2010 is now way behind us, this video is still a brilliant overview of what's going on today. Before seeing it, I didn't believed that someone can explain all this stuff in less than an hour, but Brad proved me wrong. And he did it with style.

Here are the topics mentioned in the video and the quotes that impressed me the most:

  • New JavaScript selectors - it's a sort of what jQuery gives you. You can put an arbitrary CSS selector;
  • Web Storage - It's really easy to be used, and it just persists;
  • Web SQL Database - When simple key-value pair isn't enough, another part of HTML5 is a real SQL database;
  • Application Cache API;
  • Geolocation;
  • Web Workers - they are not threads, but they kind of act like them;
  • Drag And Drop;
  • New Semantic Tags - the nice thing is that it keeps your mark-up more semantic, it helps search engines [...] and you're also making your page more maintainable;
  • New link relations;
  • Microdata - it's not trying to be artificial intelligence mark-up language, and it's learning from a lot of the lessons from the last 15 years. Right now Google will actually see some Microdata mark-ups for events, reviews, in order to get better search results;
  • ARIA attributes - one problem with jQuery UI, Dojo UI, is that screen readers can't work with them. ARIA is a way to add a little more of extra information, so screen readers know that a jQuery UI component that is a tree... is a tree;
  • New form field types - we don't have to do this with JavaScript. So a lot of HTML5 is, again... get things out of the JavaScript that don't really belong there, get them back in the browser;
  • Audio and Video - this is really in the browser, so we can add CSS reflection (and other stuff);
  • Canvas;
  • SVG - HTML5 says you can now drop these tags into the normal html;
  • Selectors - CSS gives you more of them (selectors) based on what people have asked for;
  • Fonts - it's actually from CSS 2.1 but it's finally ariving after 15 years;
  • Text wrapping - you have no idea how much pain people have gone trough, having to use server-side solution to achieve this;
  • Columns - something that used to be a pain in the but to do; you don't have to be a wizzard to do things that everyone needs to do;
  • Text stroke;
  • Opacity - this used to require custom made images;
  • HSL - the reason that matters is humans don't think of colors in terms how rgb asked you to think of colors;
  • Rounded corners - it's amazing how common things used to be so hard;
  • Gradients - with great power comes great responsibility;
  • Text shadows;
  • Background sizing and multiple backgrounds - again, you don't have to spend many hours in front of Photoshop;
  • Transition and Transforms - these can replace a lot of JavaScript.

In general, two phrases by Brad Neuberg are also worth mentioning:

It's great time to be a web developer

and

The next five years will be very exciting

The slides can be found on slides.html5rocks.com. It seems that they update the information from time to time with things that are missed, or had not existed, during the talk, which is a great way to keep yourself informed about what's going on in the constantly changing world of HTML5, CSS3 and JavaScript. Some of the new topics are IndexedDB, Web Sockets, Desktop Drag-In (File API), Desktop Drag-Out, FileSystem APIs, Device Orientation, Speech Input, Markup for applications, Form field types on mobile, Border image, Flexible Box Model, Custom data-* attributes, Element.classList, History API.

Enjoy the video.

Beyond Expertise

22 September 2011

Finally, after all this talk about expertise and becoming more expert, what lies beyond the expert? In an oddly circular way, the most sought-after thing you want to achieve after becoming an expert is...the beginner’s mind.

The professional kiss of death for an expert is to act like one. Once you believe in your own expertness, you close your mind to possibilities. You stop acting on curiosity. You may begin to resist change in your field for fear of losing authority on a subject you’ve spent so long mastering. Your own judgment and views, instead of supporting you, can imprison you.

I’ve seen a lot of this over the years. Folks invest heavily in some language, say, Java, or C++ before it. They get all the certifications; they memorize the fifteen lineal feet of books on the API and related tools. Then some new language comes around that lets them write programs much more concisely and more intuitively, test more thoroughly, achieve greater concurrency more easily, and so on. And they don’t want any part of it. They’ll spend more energy deriding the newcomer than in seriously evaluating it for their needs.

That’s not the kind of expert you want to become.

Instead, always keep a “beginner’s” mind. Ask “what if?” You want to emulate a child’s insatiable curiosity, full of wonder and amazement. [...]

Approach learning without preconceived notions, prior judgment, or a fixed viewpoint. See things exactly as they are—just as a child would.

Wow. This is cool. I wonder how it works? What is it?

Pragmatic Thinking and Learning: Refactor Your Wetware

Classical OOP in JavaScript

03 December 2010

There are two ways to look at the Object-oriented programming when it comes to JavaScript. The first one is to think in terms of classes and instances (the classical OOP), and the second one - only in terms of objects (the prototypal OOP). It is hard for Java, C# and C++ developers not to think about classes, since the classical OOP, as we all know it from these languages, relies entirely on defining the instance structure through classes and interfaces. Thus, I will first make some notes on it on this article.

Classical OOP

In classical OOP, we define a class via the keyword function. The same keyword is used to define public and private, static and instance methods. It sounds complicated, and it really is. But the reason for this is that the classical OOP in JavaScript is only a patch.

The following is an example of a fully exposed class:

var Book = function(isbn, title, author) { 
	this.isbn = isbn; 
	this.title = title || 'No title specified'; 
	this.author = author || 'No author specified';
}
// public instance method
Book.prototype.display = function() { ... };
// public static method
Book.convertToTitleCase = function(string) { ... }; 

Instances are created via the new keyword, as you may guess. The anonymous function is the class constructor.

All instances of the Book class provides three public properties (isbn, title and author) and a public method (display). The prototype property is used to attach a method to all instances of a given class (the prototype property is still to be discussed in details).

There is nothing interesting about the fully exposed classes, so we are getting straight to the private members.

var Book = function(isbn, title, author) { 
	// private attributes
	var isbn, title, author; 
	// private method
	function checkIsbn(isbn) { ... }
	// public privileged method
	this.setTitle = function(newTitle) { 
		title = newTitle || 'No title specified'; 
	}; 
};
// public non-privileged method
Book.prototype.display = function() { ... }; 

This time, isbn, title and author are private attributes. Book is in fact a closure for the public setTitle method. Thus, the setTitle method has access to the local variables of its closure. Using closures, we can imitate private attributes and methods.

Two types of public methods can be declared in JavaScript, in contrast with Java. This is not some native feature of the language, it's just that attaching a method to the this object inside the class (the closure) makes the method (called privileged method) see the private members, and attaching a method to the prototype property of the class is done outside the class (the closure) and that's why the method (called non-privileged method) does not see the private members. There are no non-privileged methods in Java.

Now, how do we declare private static members? The most famous example about a static property is a counter that counts all instances.

var Book = (function() {
		// private static attribute
		var instances = 0;
		// class constructor
		return function() { 
			instances++;
		}
})();

var book1 = new Book(); // Book.instances == 1
var book2 = new Book(); // Book.instances == 2

Note the () at the end of the function declaration. This is a self-executing function. The question is what happens to the Book variable. Our self-executing function returns another function. It is assigned to the Book. The idea is that you cannot execute the outer function any more (it does not have a name). So the local variable instances is initialized only once (this is exactly the behavior of the static members within a class). But its value can be changed by calling the inner function. Remember, the inner function has access to the local variables of its closure. You call it by instantiating the Book class.

So, speaking in terms of the classical OOP, Book is a class, instances is a private static property, and we have a constructor inside the Book class.

Static methods are declared in the same way:

var Book = (function() {
	// private static method
	function checkISBN(isbn) { ... }
	// class constructor
	return function(isbn) { 
		checkISBN(isbn);
		...
	}
})();
// public static method
Book.convertToTitleCase = function(string) { ... }

At this moment you should have noticed that we used different structures to declare static members and instance members - self-executing function and a "simple" closure. So how do we combine instance and static members? It's simple, we use the structure for the static members (a self-executing function) and declare the instance members inside the returned inner function (the constructor):

var Book = (function() {
	// private static method
	function checkISBN(isbn) { ... }
	// class constructor + instance members
	return function(isbn) { 
		// constructor code
		checkISBN(isbn);
		// private method
		var isbnToCountry = function() { ... }
		// public privileged method
		this.getCountry = function() { ... }
	}
})();

In the end, what is an Object-oriented paradigm without inheritance?

function Person(name) {
	this.name = name;
}
Person.prototype.getName = function() {
	return this.name;
}

We need an Author class that extends the Person. We do it in that way:

function Author(name, books) {
	Person.call(this, name); 
	this.books = books; 
}
Author.prototype = new Person(); 
Author.prototype.constructor = Author; 

Several things happen here. First, we don't have a native method to declare that a class extends another one. We need to rely on the prototype chaining. When we call a member on an object, the interpreter (the browser) first checks whether the method is available in this particular object. If not found, the special prototype property is used. If the value of the prototype property is object, the member is searched in this object. And the process continues to the top (while the prototype of some object in the chain is null).

When an object is created via the new keyword, a secret link is created between the new object and its class (the class is in fact a function, and all functions in JavaScript are objects). This explains why public methods are added to the instances of a particular class by adding them to the prototype property of the class. Now, get back to the beginning of the Classical OOP section to once again see the examples (and this time think only in terms of objects to understand the prototype chaining and why public instance methods are defined by attaching them to the prototype property of the "class").

Let's get back to out Author. We want all members of Person to be available to instances of Author. So we link the prototype property of Author to a new Person object. This looks strange to a classical programmer, but remember, we have to attach an actual object, and new Person is exactly that.

For every given function f, f.prototype.constructor points by default to the f itself. When the new operator is used, the interpreter looks for the value of the f.prototype.constructor. We have just changed it by changing the entire prototype property, so we need to correct the behavior of the new operator.

Finally, we need to call the super class constructor. This is also complicated. The magic function call is used. It changes the context of the Person function to the context inside the Author function. I.e. the this keyword within Person points to the same object as the this keyword within the Author.

Because of all these efforts, the string 'Dustin Diaz' is returned by the following code:

(new Author('Dustin Diaz', ['Pro JavaScript Design Patterns'])).getName();

Nice. Now let's encapsulate all the inheritance logic inside a global function extend:

function extend(subClass, superClass) {
	subClass.prototype = new superClass();
	subClass.prototype.constructor = subClass;
	subClass.superClass = superClass;
}

This works nice, except that may not be so efficient as this one:

function extend(subClass, superClass) {
	var temp = function() {};
	temp.prototype = superClass.prototype;
	subClass.prototype = new temp();
	subClass.prototype.constructor = subClass;
	subClass.superClass = superClass;
}

What we do here is to avoid instantiating the super class and in the same time preserve the prototype chain. As a result we can write the following code:

function Author(name, books) {
	Author.superClass.call(this, name); 
	this.books = books; 
}
extend(Author, Person);
 

I personally prefer to write Author.extends(Person) instead of extend(Author, Person). It even sounds better when you pronounce it (try to pronounce both loud). And it easy to be implemented. Just add a method extends on every function:

Function.prototype.extends = function(superClass) {
	var temp = function() {};
	temp.prototype = superClass.prototype;
	this.prototype = new temp();
	this.prototype.constructor = this;
	this.superClass = superClass;
}

By this time you should know how to declare and instantiate classes, how to define private and public, static and instance members, and how to extend one class from another. The true power of Object-oriented programming is seen when you apply the concepts to some design pattern. Singleton is used more in JavaScript in comparison with any other language. So here is a quick example:

var multipleEdit = function() {
	var CHECKBOX_CONTAINER_ID = 'params';
	var checkboxes;
	function initCheckboxes() { ... };
	function attachClickEvents() { ... };
	...
	return {
		install: function() { ... };
		selectRecord: function() { ... };
	}
}

This is a reusable module for checkbox handling. There is some complex logic here, but the bottom line is that we want to provide only two public methods: install (to initialized the script) and selectRecord (in case someone wants to trigger the event registration from within the html). Hence, we declare these methods inside a return statement. Again, it may looks like a magic for the most programmers who come from Java or C++. In order to understand the structure, just think in terms of JavaScript. multipleEdit is just a name of an anonymous function. All variables and functions declared inside this function are not accessible outside. The function returns another variable to the outside environment: an object with two properties: install of type function, and selectRecord of type function. The tricky part is that this object is created dynamically, using the {} notation. As a result, we can write the following code to initialize the script: multipleEdit.install().

Prototypal OOP

In the prototypal OOP, you directly create an object instead of defining its structure through a class. Then, you reuse it to create new objects and rely on the power of the prototype chaining. An article on prototype OOP in JavaScript is coming soon.

Resources

Most of the examples in this article are from the book Pro JavaScript Design Patterns by Dustin Diaz and Ross Harmes. I really liked the first part of the book, explaining both ways to think of OOP in JavaScript.

How To Draw The Attention Of The Audience

22 May 2010

One of the best places I've ever seen to learn advanced JavaScript is on ejohn.org. There are several reasons for it, but what I want to mention here is the first slide (after the summary). Our goal! Determining a goal for your audience is the best way to draw attention to the end of any presentation. In this case the effect is even bigger because the audience will have found out till the end of the introduction whether the information is relevant to them, thus whether they are interested to listen / read.

I am amazed how many lecturers failed to do that simple trick and therefore lose connection with the audience.

Progressive Enhancement Cannot Be Applied To html5 Layouts

20 April 2010

Let me first make this clear: each time you fix something for a certain browser, you are not applying progressive enhancement. Progressive enhancement is all about building for the less capable first and enhance the experience for those using the latest modern browsers. So, any type of fixes are useless. If you use fixes, you might be applying graceful degradation or, more likely, you may just be hacking around in order to workaround the differences across the browsers and to make everything look and feel the same.

One of the great features of html5 is the new semantic tags. Like section, article, aside, footer, etc. Let's see how we can build a new layout using them. First of all, we have to make them block-level elements with css since they will behave as inline in each browser that do not understand them. So we fix the fact that these browsers do not support html5 semantic tags. Oops, I used the word fix, that's an indication we're not applying progressive enhancement. Ok, that's a tiny little fix so we can ignore it. Now, another obstacle is that Internet Explorer cannot apply a style to elements it doesn't know. So we're using the html5 shiv to create the elements in the DOM Tree and to fix this bug in IE. Oops, another fix. I'm not going to continue, I believe you get my point.

Ok, but what about the degradation of our future highly semantic markup? When you apply these fixes, another issue to worry about is what happens on browsers that do not support css. All these block-level elements becomes inline and the page looks messy (remember the idea of the CSS Naked Day?) The same way as if you use only spans to build the layout. Or what happens to IE with JavaScript turned off. It still cannot see the styles related to the new elements. So, our degradation is obviously not graceful, it is, to be honest, painful to watch.

The fact is, html, no matter which version, is not related to the user experience in any way on a given web page. It describes the data on the web, it marks it up. That's it. No visualization, no behavior. So, how can we build html5 layouts using progressive enhancement? Which is the basic technology we can use before it to assure wide support? Yup, there isn't any. Of course, we can build our layouts in the old way, but then we are not really using html5, only these features that work across the different browsers, like the short doctype, short charset, etc. That's a kind of compromise, it's neither progressive enhancement nor graceful degradation.

A great example of html5 and graceful degradation is Video for Everybody! on camendesign.com. It uses html5 video features, then it fails to QuickTime if your browser is not aware of html5, then it fails to flash, then it fails to image. But can't we reverse the process? Can't we build for the one that is unable to see video by any mean and then add flash, QuickTime and in the end - html5? I think it cannot be done right now, but it's still a not explored field. I might be wrong...

html5 Videos On Youtube

15 April 2010

Go to http://www.youtube.com/html5, click on Join the HTML5 Beta link and search for a video. You have to use a web browser that supports the html5 video tag and the youtube video format, which pretty much limits you to Safari 4 or Chrome 4 by the time this article is published (Update: Firefox 4 is now on the list).

Eric Meyer demonstrates an interesting flexibility when html5 is used instead of flash.

Version 5

04 April 2010

If someone follows the URL to your web site and don't see a typical blog there, it looks ridiculous, preposterous, even tasteless. Of course what people think has never cause me to do something different from what I had in mind in first place. But it has made me think of the real cause I've changed the content, layout and the look and feel of radoslavpopov.com so many times in the last several years.

Through the years I've used this place to improve my skills as a web developer. This was the place I've first learned how to use tables to structure my content... and later to use divs for everything I could mark up... and later to use semantic mark-up, and how to separate content, styling and behavior... and what is unobtrusive JavaScript... and so on.

If we met each other in the last two years it has a good chance that you know my daily work is not related to Front-end development any longer. And I missed some epic events in the scope. The release of IE8. God help me if I need to build even the easiest layout and something goes wrong. The emerging css3 and it's support in most modern browsers. All the buzz around html5. The next big thing - fonts in modern web design.

One sunny day I got sick, stayed at home and decided that this tendency needs to be broken. I cannot afford to waste years in gained knowledge because of laziness and to become the typical server-side developer, one I used to hate so much in the near past. Besides that, I love Front-end technologies, it's just that... well... I've forgotten about this love lately.

So, this is the result - a brand new version of my web site (I called it v5 in accordance to the html5, although it should be near 10 if I'd counted correctly). It will continue to serve as a place to gain knowledge about one of the fields I love the most.

Btw, don't be too disappointed if you've opened the source only to see the old looong boring doctype. There is a reason I'm not moving too fast to the html5, but this is a topic for a future post.