Getting Started with Eclipse Part 2

Okay, so it took me WAY longer than a week to get this up, I apologize. However, as promised, here is the second half of Peter Coles’ walkthrough of Eclipse. This portion focuses on the actual installation and configuration of Eclipse. If you don’t know what Eclipse is, or want to see why Peter loves it, check out the part 1 post. Everyone else, enjoy!


Step 1
We’ll start by scooting over to http://download.eclipse.org/tools/pdt/downloads/index.php to pick up a copy of the latest stable release (currently 1.0.3). This wraps up both base Eclipse and the PHP Development Tools.

Once downloaded, unzip it and pop the eclipse folder somewhere appropriate. In Windows, I put it in the “Program Files” folder and created a shortcut to the executable file in my quick launch bar. On the Mac I put it in the applications folder and dragged the executable to the dock. In Linux…well if you’re using Linux then I doubt that you need my help on this.

Step 2
Launch Eclipse and specify where you would like to store your workspace. This is where all your files and settings will be put.

Step 3
Click on the button to the right to go to the workbench. You can explore the snazzy icons later.

Step 4
On the main menu go to Help > Software Updates > Find and Install. Select Search for new features to install and click Next. Click the New Remote Site… button and create a site called “Aptana” with URL “ http://update.aptana.com/install/3.2”. Click on Finish and it will do a search for what’s available and should find Aptana. Tick the box next to it and then click Next. Accept the license agreement, click Next and then Finish. Go make a cup of tea or take some other refreshment, this will take a while.

Once the download is complete you’ll probably be asked to install unsigned items part. Be brave, click Install All. Once completed you be asked to agree to configure your firewall to allow Aptana through (it likes to update you on new features). There’s no need to restart Eclipse yet. You have now installed the community version of Aptana Studio, but not its PHP tools (which we don’t want – they interfere with the better PDT tools) into Eclipse. You can learn more about Aptana Studio at http://www.aptana.com/studio.

Step 5
Now we’re going to add a couple of optional plug-ins from an independent source: Andrei Loskutov. Two of his plug-ins are of particular interest: FileSync and AnyEdit. FileSync allows a link to be created between a file in a project and an external location. For Kuroi this is useful to maintain the link between the development fileset and the test environment files, but I can imagine many other possible uses depending upon your workflow. AnyEdit is the plug-in that I am using to automatically replace tabs with spaces and strip whitespace from the end of lines.

The install process is similar to Step 4. Help > Software Updates > Find and Install; select Search for new features to install and click on Next. Click the New Remote Site… button and create a site called “Andrei  Loskutov” with URL “http://andrei.gmxhome.de/eclipse/”. If the Aptana box is still checked, uncheck it and click Finish. Expand the list of features until you can see all five. Select those you want (FileSync and AnyEdit Tools recommended). Click on Next, accept the licenses, Next again, Finish and then Install All. Still no need to restart Eclipse.

Step 6
Finally we’re going to install Subversive. This is the most complex installation, and it’s only marginally more complex than those we did in the previous two steps as we will need to interrogate two remote sites and exclude some options. Let’s first go to Help > Software Updates > Find and Install; select Search for new features to install and click on Next. Click the New Remote Site… button and create a site called “Subversive” with URL “ http://download.eclipse.org/technology/subversive/0.7/update-site/” (and while you’re there, uncheck Andrei). Repeat the process yet again to create another remote site called “Subversive SVN Connections” with URL “ http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/” and hit finish.

I recommend ticking the Automatically select mirrors box on the popup that appears, then OK. Check the first box and you’ll probably get a message about the “Mylyn Project.” Drilling down will show you where it’s coming from and allow you to uncheck this option. Clicking on the Connections box may result in errors (for the Mac I had to remove Win32 specific options – seems reasonable). Then carry on as for the previous options, but this time opt to restart Eclipse at the end of the process. Don’t worry if it starts up once and then restarts itself a second time, it won’t do this normally.

Step 7
Close down the welcome screen – I’ll leave you to decide whether to install the further updates from Aptana at this time. You’ll probably want to get rid of that Aptana Welcome page too for the moment.

Step 8
Let’s get in the mood for PHP. in the menu bar, go to Window > Open Perspective > PHP.

Step 9
Now we’ll set a few configs. First find the preferences menu. In Windows it’s at the bottom of the window menu. On a Mac it’s near the top of the Eclipse menu. Wherever it is, open it and go to PHP > Formatter and change the tabs to 2 spaces. Then, still in the preferences popup, back up to General > Editors > AnyEdit Tools and under the Auto Convert tab, check convert tabs <-> spaces. You want to uncheck the warning immediately below too. Then Click on OK.

Step 10
To create a new project, click on the top left icon and select New PHP Project.

Step 11
To set up a subversive link to a repository we’ll first open up a new view: Window > Show View > Other… > SVN > SVN repositories. Click on the icon with the green plus, and the rest should be obvious (if you are familiar with SVN already).


If it feels like an abrupt ending, I apologize. Peter’s walkthrough ends here, however things continue to get more interesting. The entire concept of an Eclipse project deserves a walkthrough in its own right, along with workspaces and perspectives (these Google search results will get you started, though). I strongly recommend you hit up the Eclipse Wiki and the official documentation for more information.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

The Greatest Firefox plugin

…ever.

http://amionmyspace.com

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Getting Started with Eclipse Part 1

When I went to the Zen Cart Conference in Toronto in April, I had the great pleasure of meeting Peter Coles, owner and operator of Kuroi, a web design firm based in the UK. Peter is definitely one of the best developers I’ve seen bubble up from the Zen Cart community (along with team member Chris Brown).

For the meeting, Peter put together a fantastic tutorial on Eclipse, the premier integrated development environment (IDE). I played with Eclipse in the past, but it’s so overwhelming initially that I never got the hang of it; Notepad++ always suited me just fine. Peter did a great job making the system approachable, including a step-by-step guide specifically targetting PHP developers. Needless to say, I saw the shortcomings of my simple text editor, and am currently tackling this beast.

With Peter’s permission I am happy to share his tutorial from the Toronto conference here with you (minor edits made for consistency). Today’s segment covers why Eclipse was a good choice for Peter and Kuroi (and why it’s a good choice for you!). Later this week I’ll post the actual steps for setting up Eclipse. Enjoy!


At Kuroi, we have been considering for a while a move away from Dreamweaver, to a tool that is better able to support the type of work that we are do. We both have developer backgrounds and do the vast majority of our work, development and styling, by hand coding rather than by use of the WYSIWYG interface that is one of DW’s main strengths.

Our search was motivated by growing awareness that DW simply isn’t designed for our way of working. In effect it was a glorified editor with a few nice features. We were sure that there would be an IDE (or IDE’s) that would more closely match our preferences and offer additional features that would streamline our workflow. The ideal IDE would therefore give us everything we actually use in Dreamweaver and some nice goodies to make the transition worthwhile.

This all comes with the huge caveat that I’m still at an early stage of learning how to use Eclipse, but even at this early point, I’m seeing more than enough benefits to recommend that Kuroi makes the switch.

Why Eclipse?

I looked (briefly) at a number of IDEs and one in particular in depth. Aptana is gaining in popularity amongst designers, largely because of its support for AJAX development. It has a PHP add-in and also one for AIR, which made it particularly interesting. However, I was unimpressed with its PHP editor and PHP support generally, and the discovery that it didn’t support the deployment of files across a network (i.e. to our test server). However, Aptana Studio is built on Eclipse, thus drawing my attention back in that direction.

Eclipse comes from the non-profit Eclipse Foundation which includes representatives from (amongst others) IBM, HP, Red Hat, SuSE, Ericsson, Intel, SAP, and more recently (and significantly for PHP development) Zend. The current version of Zend Studio is being sold in two forms: a stand-alone version and one built on Eclipse, which in my view is the first step in a Zend strategy to move all of its customers to the Eclipse-based version. One license fee gets you both versions.

Another factor that drew our attention here at Kuroi was that Adobe (owners of Dreamweaver and the Flash IDE) are now basing the Flex IDE (that’s the one used to Flash movies using a programming language) on Eclipse. Now that’s a vote of confidence!

So Eclipse is stable, well-supported, and building up some serious momentum, as well as providing a consistent approach to tackling an unprecedentedly wide variety of development types that previously would have required very different development tools.

Oh, and it’s free!

For us cost isn’t the primary concern, and I have also evaluated Zend Studio on Eclipse against Eclipse PDT (PHP Development Tools). But I struggled at first to find differences. They are there. The debugging is reputedly better integrated, code deployment is easier and there will surely be differences in the integration of other Zend services. But most of the basic stuff we do in DW is covered by the base functionality in Eclipse so there didn’t seem a need to splash out $399 per workstation (and we have several) at this point. However, if those extras were needed in the future, it would be possible could upgrade to Zend and benefit from the knowledge and working practises derived from use of the underlying package as the icons, look & feel and underlying paradigms are that similar, and Zend is structured as an increment to the base package.

This would be true of other tools too. The problem that I had with Aptana not supporting a network server arose in Eclipse too. I solved it by using an Eclipse plug-in and since Aptana is based on Eclipse, I had to try…and yes, it worked there too, and have a growing belief that it would work in any Eclipse-based application. And as you will see there proved to be another major benefit to this inter-operability.

Anyway, enough raving…

What do we want from it to match our Dreamweaver workflow?

We rely upon (in no particular order):

  • Syntax Colouring
  • Snippets
  • Code folding
  • File Manager
  • Working File Segregation with local and remote deployment
  • Code Search (current project and whole Zen Cart distro)
  • File Compare
  • Parenthesis Matching

So can Eclipse offer these?

Syntax Colouring
This is available by default and can be configured through Window > Preferences > PHP > Editor > Syntax Coloring

Snippets
There is a snippets view allowing common code blocks to be saved and quickly re-used. Snippets can also be exported and imported (useful for sharing). However, code completion and code templates offer even faster way of inserting blocks of code or functions in may situations.

Code Folding
Code folding is available but unlike Dreamweaver files are opened with comment blocks and functions already foldered. This is bliss (though if you don’t like it, it can be turned off too). It is so much quicker to locate specific bits of code in large files (and this is just one of the tools that helps in this.

File Manager
Eclipe’s PHP Explorer view offers a file tree similar to the file manager in Dreamweaver, but goes wider. At the top end it includes projects (rather than them being separate entitles that you must switch between à la DW). At the bottom end it allows you to drill down into some files. For example, it is possible to drill down into classes or other files containing ph functions and select a specific function or method. The relevant file will be opened with all functions closed (see above) except for the specific one selected (more bliss).

Working File Segregation and Deployment
At Kuroi we typically work with Zen Cart and Drupal, both of which are large file sets. So we segregate the files which we have changed or created from the full code set for the underlying application, and use DW to deploy our files to environments with a full installation for testing or delivery. DW allows us to define a local, test and remote file set and switch between them.

Eclipse is focused differently. It appears to be good at supporting projects based around code repositories but weak at simply transferring files to another server across a network or by FTP (or similar). However this can be dealt with.

The top ranked plug-in for Eclipse is FileSync. Installation is a breeze (and will be covered), and once in place it allows the files in a project to be linked to an external file set, such as those on our test server. Editing and saving a file in the project, automatically updates the equivalent external file. Precisely which files get updated can be set at folder or file level (as opposed to DW’s cloaking facility, which only allows folders to be excluded from updates).

Although there is an FTP facility originally developed by IBM, it appears to have a poor reputation and wasn’t easy to install (i.e. I didn’t manage it). However, Aptana’s FTP has a good reputation, and I was able (easily) to add it to Eclipse (details below). Like DW it allows bi-directional synchronization, but in place of upload and download there is a unidirectional synchronization, and no drag and drop.

Code Search (current project and whole Zen Cart distro)
Search is easily accessed by a keyboard short cut or a button on the navigation bar. The modular nature of Eclipse, and the way I have built my install, means that I have ended up a choice of four slightly different search facilities! I suspect that I could trim that down if I wished, but it’s not inconvenient. Searching brings up a results window, as in DW, but rather than showing the searched for term in context, it shows a file tree. Clicking on a result will open the file and take you to the first result in the file, or you can use the search result navigation buttons to navigate through the results, weed them or re-run a previous search. Oh, and you can do replacement too.

File Compare
DW allows the integration of third-party file comparison tools (one of us uses WinMerge, the other Beyond Compare). Eclipse has file comparison built in and when I say file comparison, I mean file compare on steroids. It will compare folders and their contents or individual files. The options available depend on the context; but contain at least “base from working copy”, “latest from repository”, “URL”, “branch”, “tag”, “each other” and “local history.” That last one means that a file can be compared with its own history, nice! There is also “help” available for three way comparisons though my poor, exploding brain isn’t ready for that yet.

Parenthesis Matching
Only joking. DW doesn’t do this. So we both switch regularly into Notepad++ which does, just for this. Happily it’s built in to Eclipse.

What Extra Goodies can Eclipse give us?

Well, that’s all the boxes ticked for what we do now. Is there anything new? Well, yes. Heaps. I can only scratch the surface here.

Subversive SVN
One of the modules that can be added into Eclipse is Subversive. An official Eclipse project, this add-in claims to use an extended API allowing it to offer features for working with SVN repositories that aren’t available in other packages. I don’t have enough experience of SVN to gauge the validity or benefits of this. But I do like being able to update SVN repositories from within my IDE with a single click.

I haven’t yet attempted to upload to a repository from Eclipse, but suspect that it would prove very simple to do.

Code Assist
Start to type a function and then press ctrl-space and up will pop a tool tip with all functions matching what has been typed so far and all functions that match what has been typed so far are made available in the a hover window for selection. Also available are details of the parameters taken by the function. The same can be done for defined constants, for which information about where they have been declared and their value is also displayed.

But it gets better. The functions and constants available via code assist don’t have to be restricted to those in the current project or built into PHP. It is possible to include a reference to another project, including a project linked to an SVN repository, and have all functions in that project also included in code assist.

And it gets even better still! If I instantiate a new class, and then type the name which I have assigned to it plus -> (e.g. $newOrder->) up pops a list of the methods available to this instance. Amazing.

Code Formatting
There’s a neat little add-in that can be applied to most editors to do things like convert all tabs to two spaces and any strip whitespace from the end of lines automatically whenever a file is saved, so you never need to worry about this again.

Multiple Editors
The extent to which this is a benefit or not is arguable, but an Eclipse installation will typically have several specialist editors, rather than DW’s jack-of-all-trades. Happily they work rather well together so, for example, I have been able to construct a template file with the Aptana HTML editor, taking advantage of its HTML code assist and completion facilities, and then switch to the PHP editor to insert the dynamic content. This is much less clunky than it sounds, since you can have the same file open in two editors at the same time and any changes made in one are immediately visible in the other.

PHP Project Outline
This offers a tree view of all constants, classes and functions in a project and the ability to jump straight to where each is declared.

Outline View
By default this is set to show the outline of a PHP file and is very useful for providing a quick overview of php scripts with classes and functions, which can be displayed in several different ways. Go to a template file and switch the view over to HTML and it displays an equally useful overview of the tag structure.

Real-time Syntax Validation
Eclipse checks your syntax as you type. If it detects a problem, it puts a little white cross on a red background next to the file and relevant line. There is a setting in the preferences that allows you to hover over the indicator in the file to see why it has been flagged.

Auto Insertion of phpDoc Comment Blocks
Write a function or method and go back to insert a comment block and Eclipse can scan what you’ve written and insert a part completed comment block, which will also contribute automatically to your project’s code assist.


Check back later this week for the follow-up, where Peter will go in depth on just how to get Eclipse going on your system, with all the features he has described above! You can save yourself the effort by simply joining the RSS feed.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Writing Modular Code - Limit Assumptions

So far in our discussion about what drives really good modular coding, I’ve presented override coding logic, and emphasized the importance of legibility and writing standards. I’ve found both concepts critical to my own coding for one big reason: they allow me to limit the number of assumptions I must make on the part of my users and fellow developers.

Let’s back up a bit. Every coder has some understanding of how assumptions work in programming (or at least you should; if you don’t then listen up). When we make an assumption, we are making a decision on behalf of whoever will be utilizing our work, e.g. “If A then B.” Here are some common examples…

  • If a user places an order in an online store, then we assume that they want a copy of the order sent to them via e-mail.
  • If a user edits an object in their profile, they expect to see some notice that their edits were applied successfully (or unsuccessfully).
  • As a developer, if I use a function that is designed to output some HTML (e.g. dropdown menu), I expect that function to output the HTML fully valid, and ready to display.

As you can see, assumptions are not an innately bad thing. The whole point of any program is to perform some repeatable action on behalf of the user. At the very least we assume that the user wants to get something done. In the course of any project, you will make many assumptions, and most will be good. To put it another way, if you make zero assumptions, you’ll be staring at a blank page of “script.”

Recognizing and avoiding bad assumptions is key, and the shortest road to success is to avoid extraneous assumptions; an assumption can’t go bad on you if you don’t make it in the first place. But every assumption you do make has some associated chance of backfire, depending on a number of factors including the target audience, action being performed, code complexity, and the skill of the developer.

Now, given all that, the key here is that most coding makes assumptions for end users. They expect hand-holding, so it is typically more forgiving. However, assumptions in modular code are made for developers. If you’re a dev, tell me how much leeway do you give to code that gets in your way? Yeah, me neither.

Since your cushion for assumption-driven errors when writing code for other developers goes to zero (for all practical purposes), you obviously want to limit the number and breadth of code assumptions as much as logically possible.

Does this code really need to perform actions X, Y, and Z all together, or can I break those actions up into separate functions/classes/scripts? X and Y really belong together, so I’ll just break out Z.

When you’ve got a choice to make and it’s too close to call, that’s when you make the assumption optional (e.g. XY by default, X or Y if specified). The answer could be as simple as an extra argument in a function, or you may need to use override logic for something more complex, like a series of classes. If you weren’t sure why I considered a discussion about overrides pertinent to a series on modular code, now you know.

Just be smart. Understand who the target audience is for your code, and act accordingly. In the end, your users–whether they be the generally non-technical public, or uber-savvy devs–will use your code because it provides some exceptional form of utility (or because their boss told them to, but that’s a whole other story).

The art of assumption management is to deliver what your audience needs, not what they want. Do that every time and you’ll be a legendary coder.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

PHP does NOT suck, and here’s why

I’m a huge fan of Jeff Atwood and his blog, Coding Horror. He writes in a very approachable manner, using a down-to-earth tone and easy-to-follow examples. He offers useful information to new and experienced coders alike. It’s the one blog I am sure to check on a daily basis. On more than one occasion, Jeff has made an insightful post about a topic that was paramount to a project I was working on. If you’ve never read his work, I can highly recommend the articles on SQL Joins, why upgrades aren’t always a good idea, passing the elevator test, and why the developer’s always at fault.

But the other day, a rare event occurred: Jeff made a claim with which I wholeheartedly disagreed. The post title, PHP Sucks, But It Doesn’t Matter, speaks for itself. Jeff lambastes the language on the whole, while freely admitting to its overwhelming success. The key quote:

I’ve written both VB and PHP code, and in my opinion the comparison is grossly unfair to Visual Basic. Does PHP suck? Of course it sucks. Did you read any of the links in Tim’s blog entry? It’s a galactic supernova of incomprehensibly colossal, mind-bendingly awful suck. If you sit down to program in PHP and have even an ounce of programming talent in your entire body, there’s no possible way to draw any other conclusion. It’s inescapable.

Well then I pulled off a movie-style escape, Jeff. I think the language is a success due to its design, and not in spite of itself. As a professional PHP developer, I think I’m also a bit more qualified than Jeff to comment on the strengths of the language.

Now, almost any discussion revolving around the pros and cons of a coding language can quickly devolve into angry flaming. Jeff of course avoids this pitfall, and I’m going to follow the same spirit of high discourse here. I’ve got two main concerns: there’s some severely flawed logic in the post, and Jeff completely disregards the many strengths of PHP, either deliberately or out of ignorance.

I responded to the logic issues in the comments of the post. Specifically, Jeff uses some fallacious arguments to back up his claim. You’ll have to read the post for yourself in order to grasp what I’m reacting to here (too long to quote). In all fairness to Jeff, I don’t believe he actually intended to make any underhanded arguments. Still, the content of the message is what it is, and ought to be addressed. Here’s the meat of what I said (modified and slightly edited):

By attempting to use facts to make a case for the languages goodness or badness, you commit a naturalistic fallacy. PHP doesn’t suck because it allows you to write function names in three different ways. It does not suck because you consider it ungraceful. It does not suck because crappy coders use it. By the same token, it does not rock because its used by some of the biggest web properties.

Secondly and to a lesser extent, you’ve got a “ post hoc ergo propter hoc” (after this, therefore because of this). Just because you used what some consider to be crappy languages in the past, does not validate what you are saying now about PHP. While I can understand and appreciate the effort to “commiserate,” I feel it is expressed under false pretenses.

The claims of suckiness tend to revolve around PHP’s hodgepodge nature; the quotes actually speak to this facet of the language more than the post itself. Summarily, because the language works around other web technologies, it lacks the elegance and cleanliness of some other languages, such as Visual Basic (his example). The effects of a lack of elegance are not discussed, but I estimate that Jeff and the quoted authors would predict some ultimate detriment to the developer or user, most likely in the form of maintainability and the prevention of software rot.

I freely admit that PHP operates as a bit of a mashup, making reading difficult at times. But the problem isn’t with PHP itself, but rather the platform for which it was developed. By its nature, writing for the web is to blend a hodgepodge of technologies. A typical web page these days is equal parts HTML, CSS, and JavaScript, all tied together with PHP. The grassroots nature of the internet compels the development of a language that grows with and as these new technologies emerge and develop. The PHP foundation recognizes this and simply rides the tide.

That being said, I see a larger issue at work here: by valuing internal code elegance over direct markup access, languages like Visual Basic and Ruby on Rails treat browser web output like some kind of necessary evil. These languages tuck the HTML and JavaScript away in built-in libraries, classes and functions, so the developer needn’t ever get their hands dirty. You can write entire websites without even looking at actual web markup.

Am I the only one who feels that this approach does disservice to developers and their users?

My opinion is 180 degrees in the other direction. I really appreciate the fact that PHP works in concert with these technologies, as opposed to superseding them. It allows me to leverage what each technology does best, independently, to achieve my target action in the best way possible. Leaving it up to my server-side code to build the majority of a web page for me sacrifices way more control than I care to give up.

Jeff thinks PHP looks bad and is difficult to maintain. Fair enough. To that, I say web development is a lot like farming: a good website crop yield still requires a guy to get his hands in the HTML dirt a little bit. Always has, always will.

Personally, I think PHP looks pretty damn cool, jumping in and out of HTML. Mix in some dynamically generated JavaScript, or really juice it up by building AJAX from PHP, and you have the makings of some “shit hot” code. I have no trouble reading it, but then again I build on the platform professionally, full-time, and write in an excessively clean fashion. I’m sure Jeff can say the same for VB, as can practically any other professional coder in the language of choice.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Using jQuery for DOM event attributes

My last post discussed my conversion to JavaScript frameworks, and why you should be one too. I explained that I settled on jQuery because it simplified how I write JavaScript without strictly locking me into a set of features and effects.

A core part of this flexibility comes from jQuery’s document ready wrapper. It works like window.onload(), but provides a quantum leap in functionality. You can find more details at the link. Suffice it to say that all jQuery event listeners must go inside a document ready wrapper.

The problem is that document ready listeners only apply to DOM elements that exist when the document is ready. It works like a snapshot. When the document is finished loading, jQuery takes a picture of how it looks and references it for activating listeners.

“So what’s the problem?” you might ask. Anything that exists in DOM after that picture is taken essentially does not exist for listening purposes. Let’s look at an example. First, here’s a simple block of HTML:


<span id="fooBar">
<a href="#" class="currentAction">generate new html</a>
</span>

…and the accompanying jQuery magic:


$(document).ready(function(){
$("a.currentAction").click(function(){
$("span#fooBar").append(
'<br /><br /><a href="#" class="newAction">new action link</a>'
);
});
$("a.newAction").click(function(){
alert('Here I am!');
});
});

The link inside the span will create a new link using jQuery. That new dynamic link has its own jQuery listener to create a second new link as well. The catch is that the second link will never work; you’ll never see that alert box listed in line 8. The jQuery DOM doesn’t have an awareness of the second link at load time, so for its purposes the link doesn’t exist. Don’t believe me? Check out the demo I put together. I’ll wait.

Weird, right? Not to mention annoying…

So how can we daisy chain page dynamics using jQuery? Simple, we just have to go old school. Since jquery can’t listen to something that doesn’t exist at load time, we have to create a new listener. The easiest way to do that is using the onclick event. Let’s modify the JavaScript code from above a bit…


$(document).ready(function(){
$("a.currentAction").click(function(){
$("span#fooBar").append(
'<br /><br /><a href="#" onclick="newClickAction(this)">new action link</a>'
);
});
});

function newClickAction(object) {
$(object).css({ backgroundColor:"yellow", fontWeight:"bolder" });
alert('Here I am!');
}

This time, the new action stands on its own as a separate function, outside the document ready wrapper. We then added an onclick event to the generated HTML, thereby creating a new listener for the new link. The alert box will appear this time, and here’s another demo to show it in action.

There are two other things to note about this second example. First, notice that we have used jQuery code inside our custom function. The magic jQuery function $() is defined in the pages global scope. Since jQuery still must operate within the normal parameters of JavaScript, that function is available inside any other function. The thing to note here is that you can use jQuery outside of the document ready wrapper. This rule applies to any JavaScript library you might use.

The second thing to note in our second example is the argument called “object” passed into newClickAction(). This variable refers to the magic JavaScript variable this, which we placed inside our jQuery-generated HTML. The variable this always refers to the object in which it is called, whether it be a function or page element. jQuery is aware of the contents of a this reference, and thus can immediately identify the element by making it the sole argument of the $() function, as opposed to getting the element by id, class names, or tree navigation (i.e. parent descendant).

The two additional concepts are put into action when you click the link. jQuery finds the element and changes the background highlighting, while showing the alert box at the same time.

As you can see, things get pretty dicey quickly with uber-powered AJAX pages. Just make sure to keep your code clean, work on a single feature at a time, and you should be fine.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Congrats, Jennifer

For those of you who don’t know, “veterinarian” is Latin for “hellish education gauntlet.”

Anyway, today was my wife’s last day of veterinary school. I just got a phone call from Jennifer saying that she is on her way home, which means she’s done! Congratulations, sweetheart, I’m so very proud of you.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Get a JavaScript framework. Now.

We’ve been really into jQuery at our office for the past few weeks, and I have to say that I am absolutely in love with it. Coming from the world of writing “classical” JavaScript in “long-hand” format, jQuery appears damn close to magic; I half-expect a mystical gnome to pop out of my monitor when I use some of the more elaborate jQuery techniques. It’s that good.

If you still do JavaScript old-school, I would urge you by any means necessary to pick up and learn one of the several standardized JavaScript support libraries. It can only speed up your JS development, decrease your bugs, and perform some really cool JS acrobatics with relative ease. If you have any aspirations of utilizing Ajax techniques, frameworks are practically a requirement. The legwork involved in setting up an Ajax request manually is a real pain.

[aside]While a framework enables relatively easy Ajax effects, I recommend you build a simple Ajax effect totally on your own. I had a background in PHP/MySQL development before I even touched Ajax, and the experience was still challenging. Now when I use framework-powered Ajax, I know what’s going on behind the scenes, which makes me a better coder. Hmm, good future post fodder…[end aside]

Any of the big-name frameworks will get you started. When making your decision about where to start, I have one piece of advice: just pick one! Each has strengths and weaknesses, depending on your skill level and how you intend to implement it. The worst way to go about this would be to go around the web looking for insider advice on which one is the “best.” You’ll only find yourself in the middle of nit-picky flame wars. Such ridiculous arguments over different coding techniques/ tools are called “holy wars.” I find the term accurate.

At the same time, I don’t want you to wonder endlessly. Here’s what I would consider the top 4 (in no particular order):

Due to the nature of my work, most of my JavaScript is custom, and so I find the more “firm” frameworks restrictive. I personally lean towards jQuery because it focused on changing how you write core JavaScript, as opposed to providing me with prefab effects and formulas. But if your needs are simpler, the more formulaic frameworks, Script.aculo.us in particular, will suit you very well.

Before you start your next project involving JavaScript, learn to use a framework.  I promise you’ll wonder how the heck you got by with out it.

Share it These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Google
  • bodytext
  • Facebook
  • Reddit
  • StumbleUpon
  • Technorati
  • NewsVine
  • Fark
  • Furl
  • Live
  • Slashdot
  • SphereIt
  • del.icio.us
  • E-mail this story to a friend!
  • Print this article!

Writing Modular Code - Make it Legible!

In the first post of my modular code series, we talked about overrides and how they are an important, and often overlooked, feature to consider in any code project. Today we will discuss an equally even more important concept: Ensure that others can quickly and easily read and understand your code.

What? Seriously?

Yes. Writing clean code is much like any other type of writing exercise, but with slightly different rules. Periods go at the end of a sentence, while semicolons go at the end of a line of code. You get the idea.

We don’t have to browse far in order to find that a lot of projects place a lot of importance on good syntax: Mambo, Drupal, PEAR, phpBB (a lot of projects, including Zen Cart, are based on this one), C++ (the big daddy), plus countless others.

The commonality between all writing formats is that you need to maintain discipline and consistency in your vocabulary. The establishment of consistent writing behavior allows your audience to focus on comprehending your message, and not waste time and brain power on first deciphering the words of that message. Again, the same rules apply to all readers, whether they be blog readers (hi there!) or fellow developers.

Even if you’re one of those coders who does his work from a dark basement, code by its very nature is supposed to be a shared. Unless you code only for yourself, your code will be viewed by other people at some point. Your work takes on an instant professional look when it’s well-formatted. Professional look means professional jobs, means professional-level fees, means 2009 Mustang GT (I’m working on that last one).

The only way you gain that ease of reading in your code is to practice and stay militant about sticking to your accepted conventions. The exact conventions you adopt are not as important as acting to own them in your coding.

The idea is much like the chores that Mr. Miyagi gave to Daniel LaRusso in Karate Kid (”wax on, wax off,” remember?). Miyagi made Daniel do the chores because they helped him develop specific muscle memories, which he applied directly to his technique training. Stick to your guns, and even when you adjust conventions, your code will still read nicely.

Want some good starting points? Listen up, Daniel-san.

Indent using spaces, not tabs.
I see tab indentation a lot in both young projects, and older, established ones, and there are several problems that come with them. Tabs display differently at different screen resolutions, on different displays, on different systems, in different programs. It may look alright on your screen, and horrendous on another.

In general, a tab pushes a ton of whitespace in front of the start of your code; in the worst cases there’s more whitespace on the line than actual code! Your uber 1900×1200 screen running Eclipse with tab stylizing enabled has no problem with 10 levels nested for loops and switches, but take pity on the 1024×768 guy, especially since he’s still holding the lion’s share of screen res on the web.

I use two spaces per level in my code. This is plenty using a fixed width font for display, though some projects do prefer four.

Keep nested logic in line with code at the same level.
All that talk about spaces over tabs means nothing if you don’t actually do it. Any code editor worth its salt will have auto-indent, which pushes the cursor to match the indentation of the previous line when a newline is created. Start there, and make sure you keep track of your nesting levels (e.g. for loop, inside an if statement, inside a switch).

Place a header comment block at the very top of every code file.
I’m talking about those blocks of code you find at the top of most files in an established project. Mambo has a very good layout description. These are important for one reason: they let people know that you made this.

You should put them in every file because never know which file a person will open first. A newbie will start high, naturally, somewhere like the index. But if they’re debugging, chances are they’ll go right to the class or function that’s throwing the error.

Plus, you never where your code may end up. If someone borrows your code, most are nice enough to give you the credit. But even if they grab the whole file, someone else may eventually wander into it. And you always hope the person who does see your stuff appreciates work, and is willing/able to pay for something custom. I want that person to know how to reach me.

Bottom line: there’s nothing wrong doing everything you can to get credit, however small, for your efforts.

Avoid inline comments ( // or # ) in favor of comment blocks ( /* */ ).
It just looks better, reads easier, and is way easier to use when you have more than one line of comments at a time. I find it useful in isolated cases to make short inline comments, however most of the time I use full-on blocks, with the opening /* on one line, the closing */ on another, and the comments in between.

Starting out go for comment blocks. It sets a good precedent and will avoid the bad habit of using single line syntax for multi-line commenting. You also must use this syntax if you intend to use a documentor with your project, such as phpDocumentor.

Use camel case or underscores, but not both.
This one deals with how you assign multi-word variables and elements. With camel case you capitalize the first letter of a new word, usually with the first word lowercase (e.g. “$myVariable”). This is the standard adopted by JavaScript. Otherwise you can break apart words with an underscore character (e.g. “$my_variable”). The choice is completely personal, neither is better than the other. Camel case saves an extra ch