Monday, April 28, 2008

An Objective Look at Javascript 2.0: Strong Typing

In our first look at the new features of Javascript 2.0, we will focus on the new typing system. We are just going to highlight some of the major changes and potential uses. For a more detailed look, take a look at the ECMAScript 4.0 Language Overview.

Traditionally, Javascript is a loosely-typed language, meaning that variables are declared without a type. For example:






  1. var a = 42; // Number declaration

  2. var b = "forty-two"; // String declaration




Since Javascript is loosely typed, we can get away with simple 'var' declarations...the language will determine which data type should be used. In contrast, Javascript 2.0 will be strongly typed, meaning that type declarations will be enforced. The syntax for applying a given type will be a colon (:) followed by the type expression. Type annotation can be added to properties, function parameters, functions (and by doing so declaring the return value type), variables, or object or array initializers. For example:






  1. var a:int = 42; //variable a has a type of int

  2. var b:String = "forty-two"; //variable b has a type of String


  3. function (a:int, b:string)//the function accepts two parameters, one of type int, one of type string


  4. function(...):int //the function returns a value with a type of int




NOTE: There has been some confusion about enforcing type declarations so I thought I'd try to clear it up. Enforcing type declarations simply means that if you define a type, it will be enforced. You can choose to not define a type, in which case the variable or property defaults to a type of 'Object' which is the root of the type heirarchy.

Type Coercion


Being a strongly typed system, Javascript 2.0 will be much less permissive with type coercion. Currently, the following checks both return true:






  1. "42" == 42

  2. 42 == "42"




In both cases, the language performs type coercion...Javascript automatically makes them the same type before performing the check. In Javascript 2.0, both of those statements will resolve to a 'false' value instead. We can still perform comparisons like those above; we just need to explicitly convert the data type using type casting. To perform the checks above and have them both resolve to 'true', you would have to do the following:






  1. int("42") == 42

  2. string(42) == "42"




While adding a strongly typed system does make the language a bit more rigid, there are some benefits to this change, particularly for applications or libraries that may be worked with elsewhere. For example, for a given method, we can specify what kinds of objects it can be a method for using the special 'this' annotation. I'm sure there are many of you who just re-read that sentence and are scratching your heads trying to figure out what the heck that meant. An example may help:






  • function testing(this:myObject, a:int, b:string):boolean




The method above accepts two arguments, an int and a string. The first part of the parameters (this:myObject) uses the this: annotation to state that the function can only be a method of objects that have the type of 'myObject'. This way if someone else is using code we have created, we can restrict which objects they can use that method on, preventing it's misuse and potential confusion.

Union Types


We can also use union types to add a bit of flexibility. Union types are collections of types that can be applied to a given property. There are four predefined union types in Javascript 2.0:






  1. type AnyString = (string, String)

  2. type AnyBoolean = (boolean, Boolean)

  3. type AnyNumber = (byte, int, uint, decimal, double, Number)

  4. type FloatNumber = (double, decimal)




In addition, we can set up our own union types based on what we need for a particular property:






  • type MySpecialProperty = (byte, int, boolean, string)




One final thing I would like to mention is that in contrast to Java and C++, Javascript 2.0 is a dynamically typed system, not statically typed. In a statically typed system, the compiler verifies that type errors cannot occur at run-time. Statically typing would catch a lot of potential programming errors, but it also severely alters the way Javascript can be used, and would make the language that much more rigid. Because JS 2.0 is dynamically typed, only the run-time value of a variable matters.

Thursday, April 24, 2008

Phantom CSS

At the heart of CSS, of course, are its selectors. They are after all what allow us to apply styles to a given element in our (X)HTML. Sometimes though, there is a desire to apply a style based on an elements state. That is where pseudo-classes come into play. You've probably all used them at some point...but there may be more there than you realize. Their value makes it worth taking a closer look.

Static Pseudo-Classes


Pseudo-classes allow us to apply an invisible, or "phantom", class to an element in order to style it. For example, let's look at the element most often styled using pseudo-classes: the anchor tag (). Some anchor tags point to locations a user has already viewed, and some point to locations the user has not yet visited. Looking at the document structure, we can't tell this. No matter if the link is viewed or not, it looks the same in (X)HTML. However, behind the scenes, a "phantom" class is applied to the link to differentiate between the two. We can access this "phantom" class with pseudo-class selectors, like :link and :visited. (Pseudo-classes are always prefixed by a colon.)

The :link pseudo-class selector refers to any anchor tag that is a link...that is any anchor tag that has a href attribute. The :visited pseudo-class selector does exactly what it sounds like...it refers to any link that has been visited. Using these pseudo-classes allows us to apply different effects to links on the page according to the visited state.





  1. a {color:blue;}

  2. a:link {color: red;}

  3. a:visited {color: orange;}



The above styles for example, will make any anchor tag that does not have a href attribute to be colored blue (line 1). Any link that has a href attribute, but has not been visited will be red (line 2). Finally, if a link is visited (line 3), then it is an orange color.

Another static pseudo-class is :first-child (The :first-child pseudo-class is not supported by IE6). The :first-child selector is used to select elements that are first children of other elements. This can be easily misunderstood. A lot of times, people will try to use it to select the first-child of an element. For example:







  1. Here is some text




Say we want to apply a style to the paragraph element. It is not uncommon to see people try to do this using the following style:





  • div:first-child {font-weight: bold;}



However, this is not how the pseudo-class works. If we think back to the concept of pseudo-classes essentially being "phantom" classes, then what we just did was apply a phantom class to the div like so:







  1. Here is some text




Obviously that is not what we want. The :first-child selector doesn't grab the first child of an element; it just grabs any of the specified element that is a first-child. The correct way to style that would be with the following line:





  • p:first-child {font-weight: bold;}



That's probably as clear as mud, so it may help to take another look at the "phantom" class:








  1. Here is some text






Watch Your Language


Corny headings aside, we can select elements based on the language using the :lang( ) pseudo-class. For example, we can italicize anything in French using the following style:





  • *:lang(fr) {font-style: italic;}



Where does the language get defined? According to the CSS 2.1 specification, the language can be defined in one of many ways:
In HTML, the language is determined by a combination of the lang attribute, the META element, and possibly by information from the protocol (such as HTTP headers). XML uses an attribute called xml:lang, and there may be other document language-specific methods for determining the language.

Dynamic Pseudo-Classes


So far, what we have discussed are static pseudo-classes. That is, once the document is loaded, these pseudo-classes don't change until the page is reloaded. The CSS 2.1 specification also defines three dynamic pseudo-classes. These pseudo-classes can change a document's appearance based on user behavior. They are:

  • :focus - any element that has input focus

  • :hover - any element that the mouse pointer is placed over

  • :active - any element that is activated by user input (ex: a link while being clicked)


Usually, these pseudo-classes are applied only to links. However, they can be used on other elements as well. For example, you could use the following style to apply a yellow background to any input field in a form when it has the focus.





  • input:focus {background: yellow;}



The main reason this is not done a lot is because of a lack of support. IE6 does not allow any dynamic pseudo-classes to be applied to anything besides links. IE7 allows the :hover pseudo-class to be applied to all elements, but doesn't let the :focus pseudo-class be applied to form elements.

Complex Pseudo-Classes


CSS offers us the ability to apply multiple pseudo-classes so long as they aren't mutually exclusive. For example, we can chain a :first-child and :hover pseudo-class, but not a :link and :visited.





  1. p:first-child:hover {font-weight: bold;} //works

  2. a:link:visited {font-weight: bold;} //link and visited are mutually exclusive



Again, there is a compliance issue here with IE6. The IE6 browser will only recognize the final pseudo-class mentioned. So in the case of our first style above, IE6 will ignore the :first-child pseudo-class selector and just apply the style to the :hover pseudo-class.

Looking Forward to CSS3


In addition to the pseudo-classes laid down in CSS 2.1, CSS 3 provides sixteen new pseudo-classes to allow for even more detailed styling capabilities. The new pseudo-classes are:





  • :nth-child(N)

  • :nth-last-child(N)

  • :nth-of-type(N)

  • :nth-last-of-type(N)

  • :last-child

  • :first-of-type

  • :last-of-type

  • :only-child

  • :only-of-type

  • :root

  • :empty

  • :target

  • :enabled

  • :disabled

  • :checked

  • :not(S)





For more information about the new pseudo-class selectors laid down in CSS3, take a look at the
CSS3 selectors working draft, or the excellent write-up by Roger Johansson. Currently, very few have decent cross-browser support, but as Johansson says, they can still be used for progressive enhancement...and in such a quickly changing field, when we can stay ahead of the curve, we should take advantage of it.

Tuesday, April 22, 2008

An Objective Look at Javascript 2.0: Looking Back

There has been no shortage of debate over Javascript 2.0, based on ECMAScript 4.0. Some people are extremely excited about some of the new features being discussed, and some feel that Javascript 2.0 is shaping up to look a bit too much like Java or even C++ for their tastes.

Whether you like the new features being proposed, think they're silly and unnecessary, or have no idea what the heck I am talking about, I think it's important to have a firm grasp on some of the changes being proposed. Doing so will help you to better understand both sides of the debate, and also help to prepare you for when Javascript 2.0 becomes available for use.

There's far too many changes and fixes to discuss them in one post, so this will be an ongoing serious of posts. I'll be taking a look at what the new language provides us and why. Hopefully by taking a closer look at all the changes, we can get a better feel for how those changes affect both web developers and javascript in general. First though, we should take a quick look at how Javascript got to this point, and the reasoning behind the changes beings suggested in Javascript 2.0.

Once Upon a Time...


Javascript has been around since 1995, when it was debuted in Netscape Navigator 2.0. The original intent was for Javascript to provide a more accessible way for web designers and non-Java programmers to utilize Java applets. In reality though, Javascript was used far more often to provide levels of interactivity on a page...allowing for the manipulation of images and document contents.

Microsoft then implemented Javascript in IE 3.0, but their implementation varied from that of Netscape�s and it became apparent that some sort of standardization was necessary. So the European Computer Manufacturers Association (ECMA) standards organization developed the TC39 committee to do just that.

In 1997, the first ECMA standard, ECMA-262, was adopted. The second version came along a bit later and consisted primarily of fixes. In December of 1999, when the third version rolled out, the changes were more drastic. New features like regular expressions, closures, arrays and object literals, exceptions and do-while statements were introduced, greatly adding value to the language. This revision, ECMAScript Edition 3, is fully implemented by Javascript 1.5, which is the most recently released version of Javascript.

Like ECMAScript 3, the proposed ECMAScript 4 specification will provide a very noticeable change in the language. As it stands now, Javascript 2.0 will be featuring, among other changes, support for things like scoping, typing and class support.

Let the Debate Begin


While some of the changes are bug fixes, the justification for the major revisions appears to be largely based on providing better support for developing larger-scale applications. With the growing popularity of AJAX, and the rise of RIAs, Javascript is now being used for much larger-scale apps than it was ever intended for. The proposed changes to ECMAScript 4 are intended to help make development of those kinds of apps easier by making the language more disciplined and therefore making it easier for multiple developers to work on the same application.

This is where the debate starts....how much do we need these revisions? Technically, we can implement a lot of the same kinds of structures using the language as it stands currently. The proposed changes are aimed at making that easier, but there are some people who worry about the effect this may have on what is currently a very expressive and lightweight language.

Which group is correct? Are the changes going to make our lives as Javascript developers easier, or force us to lose a lot of what makes Javascript such an attractive scripting language to use today? I think the only way to really judge how the changes will affect us is to take a closer look at the changes themselves and see both the good and the bad.

Wednesday, April 16, 2008

Spring Cleaning

Overall, I've been quite happy with the feedback gotten about the site so far. It's still quite young however, and therefore, there are a few changes that I thought needed to be made to help it continue to grow, and hopefully make it easier for readers to find and use the content here. For anyone interested, I thought I would highlight the changes.

First off, I've increased the focus on past posts. I decided to add a listing of the latest posts to each page, as well as a listing of the most popular posts on the site in terms of views. The idea here is to hopefully make it easier for you to find earlier posts that you may have missed that may still be worth a look.

I also decided to add full RSS feeds. I have heard a lot about the debate between partial and full feeds and wasn't sure at first how to proceed with them. Up to now, I had just been offering partial feeds. I am still keeping those, for any of you who do prefer them but I am also offering an RSS feed with the full posts in them now for those of you who prefer to have the entire article in front of you.

One new area in the footer is a listing of the galleries that were gracious enough to link to my site. I was overwhelmed by the positive response to the design of the site, and those galleries are how quite a few of you first came across the site. I thought I would finally get around to returning the favor by supplying some links back to them.

Finally, I decided to embed by Twitter status into the site. I fought the Twitter urge until March, but once I finally gave in, I've become fairly addicted. It's a makes it easy to keep connected with people who you may not converse with a whole heck of a lot otherwise, and if you are following the right people, it can be quite the news informant...lots of tech news seems to hit Twitter before anywhere else. To sum it up, you could do a lot worse for a networking tool.

Now, with all the new additions, something had to go to clear up some room. So, I decided to pull the "Things I Learned Online" section. Actually, I've wanted to do something different with that anyway, and this made for a good excuse. By only showing a couple links at a time in the side, I felt that some of the articles and tools I come across probably weren't getting the attention they deserve given their quality. I wanted a way to highlight a few more at a time, and to do it in a way that brings a bit more attention to them.

So after much hemming and hawing I decided to occasionally post a small group of links to resources, articles and tools that I have found that I think may interest you. Don't worry...I'm not going to turn into a site that posts nothing but lists of other sites, nor am I going to start doing a whole bunch of Digg-made top 10 posts. The bulk of the posts here are still going to be the same kind of content you've been seeing with focuses on technical, design, and theoretical articles...I'll just occasionally throw some focus out to other articles that I think are worth a read.

Having said all that (that was a bit more long-winded than intended), I'm always interested in improving the quality of what my site has to offer. So, if anyone has any strong opinions about any new changes (good or bad), or has some other ideas they'd like to see implemented (content or just enhancements), let me know.

Sunday, April 13, 2008

It’s Good to Be Wrong

Being wrong is a good thing. I know...I know...we've been told our entire lives that it's better to be right than wrong. I think, though, that in the design/development industry, it's good to be wrong sometimes.

Always being right means we're not challenging ourselves enough. It means that either we've become comfortable and content with where we are at with our skills, or that there is no one challenging us to improve those skills. In either case, we're not progressing.

If we're wrong, it means we're pushing ourselves to explore our limits, to continue to expand our skill set. Being wrong opens the door for constructive criticism, which in turn leads to opportunities to learn. People who are willing to tell us when we're wrong are the kind of people we should be surrounding ourselves with...they're the kind of people who challenge us to become better designers and developers.

One quote, that I believe sums it up pretty well, is by Bill Buxton a Principal Researcher at Microsoft. In his book "Sketching User Experiences", Bill has the following to say:
People on a design team must be as happy to be wrong as right. If their ideas hold up under strong (but fair) criticism, then great, they can proceed with confidence. If their ideas are rejected with good rationale, then they have learned something. A healthy team is made up of people who have the attitude that it is better to learn something new than to be right.

While Bill's quote is aimed at designers, I think the rule applies to both designers and developers. Making mistakes, getting constructive criticism, and learning from that criticism is a healthy thing. It allows us opportunities to expand our skills and grow in our field. Only through this kind of healthy criticism can our skills, and ultimately the products we produce, become finely tuned.

Tuesday, April 8, 2008

Book Review: Pro JavaScript Design Patterns

NOTE: This is the first book review to be featured here. The idea is that I will frequently review web-related books to hopefully help give you an idea of whether or not a book is right for you. The books reviewed will all be somehow related to web development or design so you will never hear me tell you how much I enjoyed Stephen King's Dark Tower series or Napoleon's Pyramids by William Dietrich....except for right now of course.

Who Wrote It?


Pro JavaScript Design Patterns is written by Ross Harmes and Dustin Diaz. Ross is a front-end engineer from Yahoo! and blogs (albeit not for awhile) about random tech topics at techfoolery.com. Dustin works for Google as a user interface engineer. You can find Dustin's musings about web development topics at dustindiaz.com. This is the first book by either author.

What's covered?


Pro Javascript Design Patterns is about...well, applying design patterns in Javascript of course. Design patterns are reusable solutions to specific, common problems that occur in development. Design patterns are more popular in software engineering, but as web applications become larger and more robust, design patterns are starting to become a bit more well known in the web development world.

Dustin and Ross do a great job of explaining different design patterns and showing how to apply them in the world of Javascript. The book starts off by walking you through some object-oriented principles as they relate to Javascript. There are sections on such advanced topics like interfaces, encapsulation, inheritance and chaining. The second part of the book dives right into design patterns. For each pattern, you get to see how to implement it in Javascript, when to implement it, and the benefits you will see. Design patterns can also create difficulties if used inappropriately, so Ross and Dustin take a look at the disadvantages of each pattern so that you can accurately determine whether or not to use it in your applications.

Should I Read It?


The book definitely holds value for any person working with Javascript and front-end development. The ideas laid out in the book can help anyone working with the language to create higher-quality, efficient code. Particularly developers who work with large scale Javascript applications will benefit from the book, as that is what design patterns seem to be best suited for.

Make no mistake, the book's title starts with the word 'Pro' for a reason...this is not a book intended for beginners. It is a very concisely written book that doesn't take a lot of time setting the tone...the authors dive right into advanced concepts and code. If you are just getting rolling with Javascript or you don't have a good grasp of object-oriented programming in Javascript, then you should probably pick up another book and come back to this later. On the other hand, if you are familiar with object-oriented programming in another language, you may find the book still manageable. That's part of the beauty of design patterns...the theory works regardless of the language...it's the syntax and implementation that can differ.

Final Verdict


All in all, I really enjoyed the book. It can take awhile to work your way through it (this is not a bed-stand book), but it is definitely worth it as the concepts addressed are invaluable to creating quality code. For anyone doubting the power of Javascript, this book is a real eye-opener. You will find that Javascript's flexibility offers a lot of possibilities and by using it, along with industry-recognized design patterns, you can develop scripts that are both easy to communicate and easy to maintain.

Great...Where Do I Get A Copy?


Wednesday, April 2, 2008

More Manageable, Efficient Code Through 5S

Sometimes code turns ugly. We add quick fixes or enhancements and our code starts to become a big tangle of functions that aren't laid out in any sort of organized fashion. Over time, our code becomes bloated, difficult to maintain and what should be simple little fixes can quickly turn into long walks through messy syntax. One way of combating this is by implementing the 5S System.

The 5S System is actually a Japanese improvement process originally developed for the manufacturing industry. Each of the five words when translated to English began with 'S' hence we call it the 5S System. Like many good philosophies however, the 5S System can apply to a variety of topics. For example, the 5S System has been applied by the Hewlett-Packard Support Center in a business context and has resulted in improvements like reduced training time for employees and reduced call-times for customers. By using the system applied to coding, we can make our code more efficient and much easier to maintain.

Seiri (Sort)


The first 'S' is Seiri which roughly translates to 'Sort'. Applied to the manufacturing industry, the goal of sorting was to eliminate unnecessary clutter in the workspace. The idea here is that in a workspace, you need to sort out what is needed and what is not. If you eliminate all of the items that are not necessary, you immediately have a workspace that is cleaner and thereby more efficient

Applied to coding, this can mean going through our code and determining if we have any lines of code that are really just taking up space. This can be things like error checking that has already been done at a previous step, or if working in the DOM, retrieving the same element in more than one function, instead of simply passing a reference to the element. This definitely applies to CSS code as well. There are very few stylesheets in use that don't have a line or two that are really just unnecessary because they either accomplish nothing different than the user agent's default behavior, or are being overridden elsewhere.

Seition (Straighten)


The next 'S' means to straighten or 'sort in order.' This step involves arranging resources in the most efficient way possible so that those resources are easy to access.

For coders, this means going through and making sure that functions and code snippets that are related are grouped together in some way. This can be done by a variety of ways. If you are working with server-side scripting, consider placing related code together in an include. In CSS, use either comments or imported stylesheets to separate style declarations based on either the section of page they refer to or the design function that they carry out. (Typographic styles in one place, layout styles in another). In object-oriented programming, organize your code into logical classes and subclasses to show relationships.

Seiso (Shine)


The third step laid down in the 5S system is the Shine phase. This involves getting and keeping the workplace clean. This is an on-going phase that should be done frequently to polish up anything that is starting to lose its luster.

As we go back and work on code, we can often start to get lazy and just throw things wherever and use messy coding techniques because it's quick and dirty. The long term result of that though is unorganized code that is difficult to maintain. The phase requires a bit of discipline, we have to be willing to keep an eye out for portions of our code that are becoming a bit unwieldy and take the time to clean it up so 6 months down the road we aren't pulling out hair trying to remember what the heck we were thinking there.

Seiketsu (Standardize)


The Standardize phase involves setting down standards to ensure consistency. We can apply this to our coding and make it much easier both for us in the future, and for new employees who may have to try and work with some of the code we have developed.

Standardization in code can come in a variety of forms. We've seen some standardization in coding for-loops for example. In a for-loop it is very typical for people to use the variable i as the counter variable throughout the loop. Coders of various levels of expertise recognize the variable i in those situations very quickly and easily, because it is used so frequently.

You can also standardize the way you format your code. Some people prefer to indent code inside of loops or functions for readability, others don't. Whatever the case may be, be consistent with it. Having a consistent coding style makes it a lot easier to come back to that code later and be able to quickly locate where that new feature needs to be dropped in.

Shitsuke (Sustain)


Finally, our last step is to sustain the work we set down in each of the previous phases. This is perhaps the most difficult phase of all because it is never ending. There is a definite level of commitment to the process that has to be displayed here in order for us to continue using and utilizing this process when we code. We can't be satisfied with doing this once or twice and then letting it go. If we work to continually implement this process, we help ourselves to create more manageable and efficient code from the start of the development process to the conclusion.