Ajax and the fancy “Web 2.0″ trend are causing all sorts of web applications to pop up. The most familiar examples are the many services that google is making available, and gmail especially. Gmail is, for many people, a desktop mail client replacement. And why not? It contains the functionality that one would expect in a desktop application – viewing mail, composing new messages, and creating filters to sort incoming articles of text. It is a nicely packaged application with a decent interface. It does however have one major flaw: it doesn’t control the application used to view it.

We aren’t talking cross-browser compatibility problems or the folks using text-only browsers such as lynx. The issue that spans all browsers is that they contain navigation buttons. Back, forward, and refresh, these are all elements that can make the execution of a web application occur in an order unintended by the developer. From a software engineering perspective, this presents new problems previously not encountered when designing and developing software. From a programmer’s perspective, this introduces new complexities in the code because the state of execution can change at any time. Additionally, the code monkeys have to handle sessions that may not terminate properly, half-open connections, and navigation issues that will creep up from the user jumping around your application.

A solution to this problem that hasn’t been completely explored is to combine the benefits of desktop applications with the advantages of web applications. Desktop applications are self contained, meaning the interface to that application is completely controlled by the developer. The state of execution again becomes reliable, hooks into the process’ termination can execute cleanup code, and even cross-browser issues may be ignored. Web applications need only a web browser to load them. By embedding the rendering engine of your web browser of choice (as far as I know, Mozilla’s, Internet Explorer’s, and Safari’s rendering engines can be embedded) in an application, the only thing the user see is exactly what you want them to.

The only complication that arises from this situation is the initial distribution of your application. But because the desktop ‘launcher’ application is going to be nothing more than a frame with some logic to handle any initializing or cleanup you wish to do, it is going to be a very small download. And if you are a company that produces a lot of applications, your launcher can be modified easily to support all of them from a single application. Attractive, isn’t it? This also allows for targeting an older demographic that has been slow to catch on to web trends by deploying to them something familiar: an icon on the desktop to be click clicked.

Now for the business stuff. If you already have a solid web application that conquers the navigation and other issues that plague them, you are one step away from redeploying your application to a new market. And while speaking of markets (and thus money), if your application is driven by advertisements, controlling the platform means that the user won’t be able to block your ads. Physical distribution also becomes possible at this point. Your launcher could be bundled with an installer and distributed by CD to be sold on the shelves in brick and mortar establishments. Now your application will be reaching all corners of the current software markets, bridging gaps of technical understanding, and all without your users blocking the media you want them to see. If you are just starting development with this paradigm in mind, you are going to save development time which can be refocused on implementing features for your users. The result is a better web application that is available to everyone.

The benefits gained don’t take a lot of convincing to sell. Simplified development, a cleaner application, and reaching broader markets all from changing the means of distribution?

Money. 

We’ll start this one off with a link. Don’t worry, it is just an image (safe for work, too).

The Greatest Programming Tip Ever.

I laughed when I saw that initially, then the title hit me. That really is the Greatest Programming Tip ever. Or at least it should be on the list of top 10 Great Programming Tips, if there were such a thing. Regardless of whether you are working on an assignment for a class, a personal project, or a product for your employer, it is almost certain that someone is going to look at your code. Writing readable and easily maintained code is important for this reason, but for different reasons.

If you are going to be writing code for a class, you had better put some time in making sure your code adheres to your department’s style guidelines. For the computer science department at RIT, this was actually factored into our grades on labs and projects. Even if it weren’t, your professor is going to be more frustrated than impressed with a piece of code that lacks comments and is filled with ternary operators. Comment your code to explain things that aren’t immediately obvious to a first year CS student, name your variables to be descriptive of their function, and make sure your program flows well (no spaghetti code). This will make your professor happy, thus boosting your grades.

For personal projects, it is just as important to follow the guidelines above. While there may be no one grading your work, consider that friends, future employers, and future-you may look at the code later. Embarrassingly, I can’t even count the number of times I’ve rewritten those run-once-every-three-months kind of scripts because I didn’t take the time to comment them. And if I had put those scripts on a public source repository (which I fully plan to set up soon), employers would eventually see it. I want the code I present to the world to reflect that I am a proficient, clean coder. You should want that for yourself.

Now here is the big one, your employers. If you are working for someone, that almost definitely means you are working on a team. In this case it isn’t just a matter of writing readable code so you can remember what you’ve done when you later have to fix a bug in the code. No – things have become amplified to a factor determined by the number of people on your team and the number of those team members that have to maintain your code. I know from experience the pain and delays that can be caused by terrible code, and I won’t lie: it happened way more often than I’ve blogged here. It dragged down the morale of our project team, caused huge delays in our production (on the magnitude of weeks of developer time over the past six months), and made the codebase impossible to maintain cleanly. You do not want to be the guy that is responsible for that. Best case is you lose your job, worst case is management turns a blind eye to the project team hiding organic material in the corners of your office (give it a couple of weeks, you won’t enjoy it).

Go out and do some reading on writing readable and maintainable code. Aside of learning the basics of a language, it is the single greatest thing you can do to improve your abilities as a programmer.

This happened last month, so to some of you I am sure this is old news. But for those of you who just want a great read, you should check out this article on Linux kernel developer Con Kolivas, and why he quit kernel development forever.

Why I quit: kernel developer Con Kolivas | APC Magazine

Con did a lot for the kernel as far as desktop enhancements go, so anyone who has used Linux with a kernel >2.4.18 owes him some measure of thanks. I really recommend the article above, the guy had no formal training in computer science, nor did he know how to code before he started working on the kernel. He taught himself how to code by looking at other people’s patches being submitted to the kernel, and became the most well known developer-advocate for Linux on the desktop. Kudos to him – I’m sorry to see him go.

Now all we need are replacements! To anyone who may stumble across this blog, why not take an interest in the Linux kernel? A great introduction on how to get started comes from another kernel developer, Greg Kroah. This is a link to his presentation (it reads very well) on the Myths, Lies, and Truths About the Linux Kernel from his OLS 2006 keynote. All you have to lose is time with your girlfriends!

I ran across a problem where I had incoming socket streams taking a really long time (25-65 seconds) to read from. I knew the data was leaving the client application, and the incoming connection socket handling code was running correctly, so the only thing holding up my server handling the data was the speed at which that data was being read from the socket. Additionally, this was all running on a local loopback so network latency wasn’t the issue.

The solution was simple: while I was manually flushing the socket OutputStream on the client side, I had forgotten to close the socket explicitly (which forcefully flushes the socket’s streams before closing). Once this modification was made to the client, the data appeared instantaneously on the server.

So when doing I/O, don’t forget! Flush and close your streams and sockets!

The attendance database project I’ve recently written about requires the use of iButtons for verifying the physical presence of members at meetings. Having never worked with either the hardware other than as a user of it nor the software SDK in any capacity, it was a learning experience. One thing I quickly ran across when developing the software to locate a plugged-in adapter and read the iButton’s ID was the incredible amount of time it took to enumerate through the available ports just to find a connected adapter. The SDK provided examples on how to go about locating connected adapters, but to improve the speed at which it runs we can take advantage of what we know about the system and exploiting the code’s error conditions.

During installation of the 1-Wire drivers needed to communicate with iButton adapters, you have the option of selecting a default port to which the adapter will be connected. This information is stored as a property the SDK knows how to locate. The first step to increasing the speed of locating an adapter is to use this information – simply check the default port before searching all other ports on the machine. Odds are higher that the adapter is located on that port than any other port on the system, and by placing it as the first check before serially searching all other ports you increase your chances of getting on the first attempt.

The second enhancement requires a bit of background information. The example provided in the SDK shows you how to search all possible adapter types, then all possible ports for that adapter, and print them out. To be useful we would want instead of printing out the adapter and port names to attempt retrieving the device connected there. This would logically be done using the static getAdapter(String adapterName, String portName) method of the DSPortAdapter class. However, the time this method takes to return whether the adapter exists could be measured in seconds. To make this faster using our understanding of the system, we could skip over adapters we know we won’t be using (network adapters, parallel adapters, serial adapters, etc) and avoid scanning for them over all ports entirely. Reducing the size of the problem reduces the time it takes to come to a solution.

That is not all we can do, however. For some reason, if you try to retrieve an adapter using the getAdapter method and attempt to tell if it is successful by comparing the return object against null, it takes a long time. In comparison, the method throws an exception if it cannot locate the adapter much more quickly. Using this last bit of information, by putting a continue statement in your exception catching code you can just skip the attempt to open the obviously unavailable reader and enjoy a nice speed boost.

Here is some example code illustrating what I’ve talked about, excluding rolling over adapters we don’t care about. The speed of this is much faster than my first attempt, from taking around five minutes to locate an adapter to around 30 seconds. Base of code taken from the examples provided in the 1-Wire Java API. Sorry about the indenting, I gave up trying to figure out how to adjust the tabstop!


/**
 * Locate a reader to communicate with.
 *
 * @return boolean - true if adapter was found, false otherwise.
 */
public boolean locateAdapter( ) {
	boolean found = false;
	while( !found ) {
		try {
			DSPortAdapter adapter = OneWireAccessProvider.getDefaultAdapter();
			System.out.println(”Adapter ” + adapter.getAdapterName() +
						” found on port ” + adapter.getPortName());
			this.adapter = adapter;
			this.port = adapter.getPortName();
			found = true;
		} catch(Exception e) {
			System.out.println(”Adapter not found on default port, trying all ” +
					“available to the system…”);
		}
		if( !found ) {
			DSPortAdapter adapter;
			String port;
			// get the adapters
			for (Enumeration adapter_enum = (Enumeration) OneWireAccessProvider.enumerateAllAdapters();
				adapter_enum.hasMoreElements(); )
			{
				adapter = ( DSPortAdapter ) adapter_enum.nextElement();
				System.out.println(”Trying adapter ” + adapter.getAdapterName() );
				// get the ports
				for (Enumeration port_enum = adapter.getPortNames();
					port_enum.hasMoreElements(); )
				{
					port = ( String ) port_enum.nextElement();
					System.out.println(”trying port ” + port );
					try {
						OneWireAccessProvider.getAdapter(adapter.getAdapterName(), port);
						this.adapter = adapter;
						this.port = port;
						found = true;
					} catch( OneWireException owe ) {
						// Just continue…
						continue;
					}
				}
				if( found ) {
					break;
				}
			}
		} 

		if( found ) {
			System.out.println(”Adapter found! Using ” + this.adapter.getAdapterName() +
					” on port ” + this.port );
		} else {
			// Wait 5 seconds before trying again
			try {
				Thread.sleep( 5000 );
			} catch (InterruptedException ie ) {}
		}
	} 

	return found;
}

Java GUI Development

June 19, 2007

I’ve inherited a decently complex graphical interface to add functionality to, all written in Java. The previous developer who originally designed the interface (and who is also no longer with the company) used NetBeans to accelerate the process. While not bad in itself, the results are horrifying.

I now have a couple hundred lines of variables named along the lines of “jPanel18″ and “jTextField3.” There are three separate layouts being used across the many panels. Not a comment is to be seen, except for what was provided by NetBeans’ auto-generated comments, which have nothing to do with the code and everything to do with “this is auto generated, don’t edit.” To make things worse, the form file that accompanies the source for NetBeans is almost two years out of date, and a lot of functionality and structure changes have occurred since then leaving me to do all the editing by hand.

Tips I suggest for those thrown into situations like this:

  • Put a TitledBorder around each panel with the panel’s name. Now that you know which panel goes where, write it down.
  • Seriously, draw a picture. When working with generically named components, you’ll appreciate having a ‘map’ of where everything is going.
  • Refactor. If you can rename the components without breaking things, give them useful names (Eclipse makes this easy). If nothing else, move the components into groups of functionality or physical geometry in your initialization method.
  • Read up on the layouts being used. If you know how to work with the layouts within a panel, you’ll spend more time coding and less time making a single modification, rebuilding, and running your application to see how the change affected things.
  • Learn from this painful experience, and don’t do this in code you write in the future.

May you be blessed with patience. You’ll need it.