Out of Hanwell

December 27, 2005

Filtering Arrays

Filed under: Uncategorized — Matthias Miller @ 7:12 am

Looping through arrays and filtering items can be a real pain. If you loop through it from start-to-end, you need to remember to decrement the counter when you remove an item. For example:

for (var i = 0; i < a.length; i++) {
if (!shouldIncludeItem(a[i]) {
a.splice(i, 1);
i--;
}
}

Alternatively, you can loop through the array from the end to the start. For example:

for (var i = a.length - 1; i >= 0; i--) {
if (!shouldIncludeItem(a[i]) {
a.splice(i, 1);
}
}

Last week I was looking at a problem like this with a coworker. As an alternative, I suggested that we treat the array something like a circular list, pulling items from the start and pushing it onto the end. The code looked something like this:

var items = a.length;
while (items) {

var item = a.shift();
if (shouldIncludeItem(item)) {
a.push(item);
}

items--;
}

The caveat, of course, is that if you break out of the loop before examining all the array items, the array will be left in an unexpected order. However, I found it to be a natural way to filter items from an array.

Take your pick.

Advertisements

December 22, 2005

Ajax Unwired

Filed under: Uncategorized — Matthias Miller @ 7:14 am

The last issue of Dr. Dobb’s Journal had an article about using Ajax to monitor Wi-Fi connections. The Ajax solution is very typical, but the problem it solved is a bit unconventional:

For instance, a challenge I recently faced involved developing a web application that would serve as a session-management mechanism between a Wi-Fi server and users connected to the wireless network. The browser was the only software I could use on the client side, and because the user group was diverse, it was not realistic to require a specific browser. Users would log on via a web form, and a popup window would tell them how long they’d been connected and so on. If this window was terminated, the connection was lost. The most important thing was that this window would have to periodically connect to the server using HTTP to inform of the user’s presence and refresh with new information. The reason for that was that because users could theoretically stay online forever, the system needed to know exactly which users were online so that resources would be allocated in an optimized way. Also, this would facilitate a billing method according to how long users stayed online, not on how many kilobytes were downloaded (as is usually done).

December 20, 2005

Good Work, Channel 9

Filed under: Uncategorized — Matthias Miller @ 9:58 am

Kudos to Channel 9 for some interesting videos the past several weeks (in chronological order):

Surendra Verma: Vista Transactional File System. Transactions are nothing new, but the implementation of a transactional file system has a widespread impact, especially for networked file access over a VPN or a wireless connection. Data consistency becomes easy.

Concurrency and Coordination Runtime. This is a library (written in C# 2.0) that deals with the problem of concurrency of asynchronous operations. The typical multi-threaded locking model works great in certain situations…until you’re deadlocked. This library uses messaging (via delegates) to notify threads of events.

Singularity Revisited. Here’s a second look at an operating system written completely in managed code, going into a bit more detail of how the kernel works, such as how memory is shared between multiple processes. This project is simply amazing.

Cleartype Team – Typography in Windows Vista. Bill Hill’s a favorite, explaining the various problems typographers face. How do you make fonts readable at low resolutions? How do you design screen fonts to reduce eye strain? What about a monospace font designed for programmers?

Don’t be bored over the holidays.

December 14, 2005

More Tough Questions: Can You Code Without Running Your Server?

Filed under: Uncategorized — Matthias Miller @ 7:19 am

Modularity is a good thing in your client-side code, but it should not stop there. Just as you need separation between the HTML, JavaScript, and CSS, you also need between the client and the server. Consider the following problems:

  • You need to log in before you can access the web page you’re working on.
  • You want to be able to migrate to another server without rewriting all the HTML.
  • You’re tired of waiting for that external data source to give back information so that you can see the result of the latest tweak to the HTML layout.

Here’s the tough question: Can you code your HTML, JavaScript, and CSS without running your server?

Imagine a PHP script that downloads comics from various sources on the Internet and caches them on your hard drive. You start with a main page looks something like this:

<h1>Comics</h1>
<?php
require(‘_comicscache.php’);
$comicsCache = new ComicsCache();
$allComics = $comicsCache->getAllComics();
foreach ($allComics as $comics) {
?>
<h2><?php echo htmlentities($comics->getTitle()); ?></h2>
<img src=”<?php echo htmlentities($comics->getImageURL()); ?>” />
<?php } ?>

To solve the first problem, you change your script so that it can be viewed locally (uninterpreted) in your web browser:

<h1>Comics</h1>
<script language=”php”>
require(‘_comicscache.php’);
$comicsCache = new ComicsCache();
$allComics = $comicsCache->getAllComics();
foreach ($allComics as $comics) {
</script>
<h2>
<script language=”php”>
if (true) echo htmlentities($comics->getTitle());
else {
</script>
Title
<?php } ?>
</h2>
<script language=”php”>
if (true) echo ‘<img src=”‘ . htmlentities($comics->getImageURL()) . ‘” />’;
else {
</script>
<img src=”icon.gif” />
<?php } ?>
<?php } /*foreach*/ ?>

Yuck. It turns out PHP does not fit this model very well. The code is very verbose and hard to read, a maintainability nightmare waiting to happen. But then you remember something about your JavaScript, CSS, and HTML. They’re all in separate files; can you somehow separate your PHP from your HTML?

You create an HTML file that can be viewed offline:

<h1>Comics</h1>
<–start_comics–>
<h2>$Title</h2>
<img src=”$ComicsStub.gif” />
<–end_comics–>

Then, you write a little PHP script that does the following:

  • Find the “comics” section.
  • Replace “$Title” and “$ComicsStub.gif” with the appropriate values for each of the comics.
  • Replace the “comics” section with the generated code.

Of course, this template has limited capabilities, but by the time you’ve creating your tenth or twentieth web page, you’ll have refactored your PHP script into a powerful HTML templating framework. By doing this, your code can be reused in another server, in another language. You can automate tests for your pages without threading interactions through your server. You don’t have to jump through hoops to see changes to your HTML.

You need to answer even tougher questions: How much does modularity matter to you? How modular is “modular enough”?

December 12, 2005

Using Firefox on Different Platforms

Filed under: Uncategorized — Matthias Miller @ 4:50 pm

Having discovered a new keyboard shortcut this weekend, I think I’m finally learning how to use Firefox to efficiently surf on the platform of my whim. Because the different operating systems have slightly different standard shortcuts, I’ve been relearning my keyboard shortcuts to make it easier to switch between Windows, Linux, and Mac. (I use Firefox on all platforms; these shortcuts also apply to Safari, except that Safari does not support tabbed browsing.)

  • Ctrl/Cmd + L: go to the location bar
  • Ctrl/Cmd + F: search web page
  • Ctrl/Cmd + T: new tab
  • Ctrl/Cmd + Page Up: previous tab
  • Ctrl/Cmd + Page Down: next tab
  • Ctrl/Cmd + W: close tab
  • Shift + Ctrl/Cmd + W: close all tabs

Update: A friend of mine pointed out another shortcut that is certain to come in handy–simply pressing / opens the Find in Firefox. Unlike Ctrl/Cmd + F, it also clears the search text. This works on Windows, Linux, and Mac.

December 10, 2005

Professional JavaScript for Web Developers

Filed under: Uncategorized — Matthias Miller @ 1:19 pm

I’ve been reading parts of the book Professional JavaScript for Web Developers (Wrox Professional Guides) this week.

The first part of the book gives an overview of the JavaScript language. It has an excellent discussion of objects, including the concept of prototyping and of inheritance. It goes beyond semantics, presenting the ideas behind JavaScript objects. This is great foundational knowledge.

From there, the book becomes more of a reference guide, although more readable than, say, the JavaScript Bible. The second part of the book describes how JavaScript ties in the Browser/Document Object Model, with a helpful chapter on event handling. The final part of the book focuses on specific challenges in cross-browser web development, most notably drag and drop, error handling, XML parsing, and client-server communication.

Overall, I like the book, although I have two complaints. First, the book suggests checking for undefined values by comparing against undefined (oVariable == undefined). However, undefined is not guaranteed to be undefined; nothing keeps a coder from either accidentally or intentionally setting the value of undefined (undefined = true;). It would be preferable instead to check the type of the variable (typeof oVariable == "undefined"). Second, the 36 pages on browser and operating system detection was an overkill. All of it could have been eliminated and none of it would have been missed.

Despite its few quirks, this is a great book for those who want to go beyond a copy-and-paste tutorial and delve into the JavaScript language.

December 6, 2005

Modularity: Tough Questions for Rugged Design

Filed under: Uncategorized — Matthias Miller @ 8:56 pm

Web development is liquid. What looks nice today may not look nice tomorrow, and what works today may not work tomorrow. Requirements change, and your web page needs to be ready to meet these changes. To survive, it must be modular.

Many web developers are familiar with the ideas of modularity in the main parts of a web page:

  • HTML files contain the document.
  • CSS files contain the styles to render the document.
  • JavaScript files contain the code to interact with the document.

Three simple questions reveal the modularity of a web page:

  1. Do HTML, CSS, and JavaScript reside only in the respective (separate) files?
  2. Is the shared knowledge (contracts) between these parts clear and distinct?
  3. Could parts of this web page easily be added to another web page by duplicating only simple HTML and no CSS and JavaScript?

These questions may be difficult, but they are important because they will determine the lifespan of your web page. By keeping these pieces separate, you can centralize assumptions about the layout and behavior of the page. You can easily change the requirements or reuse your code without tweaking assumptions that are scattered throughout your page. The alternative is code that is brittle to change.

Modularity matters.

December 1, 2005

JavaScript Skyscrapers

Filed under: Uncategorized — Matthias Miller @ 10:51 pm

For many years JavaScript has been the glue for web pages, adding just enough functionality to make pages feel less static and more interactive. But this has already begun to change with Ajax applications as people start exploring larger-scale web applications that use more complex, more extensive JavaScript. This has caused Peter-Paul Koch (QuirksMode) to raise the question on his blog, “Who will develop these applications?”

Let’s face it: most of the independent pieces of JavaScript code that you see in web pages is quite small-scale–just big enough to save you the trouble of accidentally submitting your order without entering a credit card number. These scripts fit the thin-client model of the web and they all have one thing in common: any data that they might need must be downloaded with the page. What if you wanted to use auto-completion for the town or zip code? It’s impossible!

To really have a dynamic web page, you need to have access to these databases of information. You cannot simply download the database; you need a way of extracting the information you need, and only the information you need. And that’s where Ajax comes in, by allowing you to hook up with an external data source without shoving large parts of the database down the wire. With Ajax you can get pretty close to writing a thickish sort of application.

An application like this, however, has some serious design hurdles. Interactions are no longer limited to forms and hyperlinks from the client and HTML, CSS, or JavaScript from the server. Clients can trigger requests through a JavaScript function call and the server can respond in XML, or any format that is desired. The interaction between the client and the server can no longer be depicted by a simple page flow; it now involves button clicks, user entry, or a sudden change in the weather. With great interactivity comes great complexity.

How do you build a JavaScript skyscraper?

It’s all about design. On a high level, you need to have a good application model. Unless you have a clear idea what your application is going to look like, you’re likely to spend a lot of time implementing the wrong thing. You need an experienced software architect as a visionary and a leader.

On a lower level, you need to make abstractions. Force yourself to localize your complexity; create objects that have an easy-to-use interface and that allow you to refactor and extend your code in the future. Make code that easy to unit test.

Be modular. When you build a widget, localize all knowledge of the DOM. If you have an object that represents the widget on a high level, you can not only reuse the widget in other pages, but if you tweak the HTML for the widget, you can correct the logic in one place instead of in dozens of scattered functions.

If you need to do everything, get yourself one of those JavaScript libraries that can do everything. Otherwise, build your own library. As you develop your application, you will find patterns in your code. Break out this code into pieces that you can reuse throughout your project.

Be constantly learning. Watch for new ideas, new techniques, new patterns. Be ever willing to try something new, but don’t give up because it fails miserably.

Will you be the one to build a JavaScript skyscaper?

Create a free website or blog at WordPress.com.