Software That’s Wrong and Knows It, Hungarian Notation

Minor Update (May 18, 2005): Hyphenated long variable name, it was causing havoc with WordPress alignment.

Joel Spolsky explains that wrong code should be constrained to look wrong. I like this idea … arrange things so that any evil code has a look of outright guilt. Joel focuses on naming conventions, but also lists several other worthy practices which serve to highlight wrong code:

  • Keep functions short.
  • Declare your variables as close as possible to the place where you will use them.
  • Don’t use macros to create your own personal programming language.
  • Don’t use goto.
  • Don’t put closing braces more than one screen away from the matching opening brace.
  • The part about naming is interesting, and provides another argument for naming things carefully:

    The thing I want you to notice about the new convention is that now, if you make a mistake with an unsafe string, you can always see it on some single line of code, as long as the coding convention is adhered to

    Hungarian notation, he explains, was meant to be about distinguishing between types in the high-level, semantic, sense, rather than types in the int-versus-float sense. True, but Hungarian is not the only way to do it. High-level qualifiers should certainly be captured in variable names, but Hungarian prefixes are not the right way to go about it because they degrade readability. Thankfully, conventions in Java and most other languages stay clear of prefixing variables with cute 2 or 3 character prefixes.

    So, in Joel’s example, “us” is the prefix for “unsafe” and s for “safe” (I’d probably call them “raw” and “escaped”, but it’s only an example and not the main point here). Personally, I’d rather see a variable called “unsafeAddress” than “uAddress”. With the devoted Hungarian notation, it would probably be a lot worse too: “uszAddress” or something. Code is a lot clearer when you can read the name aloud, and it also improves communication among developers. What are the objections to full qualifiers as opposed to abbreviations?

    • “But you have to type more!” You’re still typing? That’s, so, like, last week. With a completion feature in the IDE, you’ll rarely if ever have to type anyway (Ctrl-Space in Idea, Ctrl-P in Vim, etc). Ed’s your friend, get to know Ed, and all that.
    • “But the code won’t fit on one line!” Really verbose names will push you over 80 columns, and that’s best avoided. It could happen on occasion. Consider 2-column indenting, for starters – it actually looks better than it sounds. I’d advocate 120 or 160 characters anyway, given modern screen sizes and resolutions, but even with the quaint 80-column standard that was all the rage in the early 1900s, qualifiers won’t push you over often.
    • “But there will be a proliferation of prefixes!” Nup. That will only happen if you’re using prefixes for redundant details like variable type. If you’re using it for sensible, high-level, concepts, you won’t be bitten by an uncompromisinglyResilient-NullableVariDiddlyaDoodlyableName. (Long names can be useful as a transition thing, ideally only for a day or two until a clearly name emerges, at which point someone can digress for 7 seconds to hit Shift-F6 and enter a better name.)

    Incidentally, one Hungarian-like convention I’ve occasionally seen in Java is capitalised statics. As in:


    I really like this convention. It provides a little bit of useful information without suffering from the main problems of Hungarian notation. It can still be read out loud as before, and adds no extra length to the name.

    Wikipedia/MediaWiki Usability Blooper: “Edit This Page” Tab is Overloaded

    Tabbing is a simple mechanism, popularised by Amazon in the late 90s, for websites to support navigation. Wikipedia (or any mediawiki-powered site) uses a tab metaphor to break down a page into Article, Discussion, Edit This Page, History. Which is more useful than other wikis that place these links in random and exciting places.

    However, the Edit This Page tab is broken. If you’re in Article, it edits the article. If you’re in Discussion, it edits the discussion. It does say “Edit this Page”, so it’s an improvement on the raw “Edit” of the current mediawiki release, but consider the many new users of Wikipedia … what’s a “page”? The main content or what I’m looking at now.

    The problem here is the metaphor doesn’t work. A tab is metaphor for a physical space, and should therefore be stateless. You don’t expect the contents of a physical space to change based on what you’re doing right now. The result is a lack of predictability: the user is not quite sure what will happen when they click on the tab. Admittedly, the consequences are low. But it could stop a user editing content. If they were in the Discussion age and they wanted to change something, they might reasonably assume the Edit tab concerns the main page, and fail to find Edit for the discussion.

    I’d suggest this:

    • Split Article into two “Siamese Twin” tabs – “Article” and “Edit” tabs, in almost complete tab form, and joined at the hip. Minor risk that the user will misfire due to them being so close, but the gain in understandability is worth the trade-off.
    • Or, if we really want to conserve the tab quantity, make it obvious that “Edit” is a magic tab … use a slightly different shape and, in a different colour, show what will be edited when the user clicks on it. e.g. “Edit Discussion”. If we’re going to exploit the magic of computers to make the tab behave dynamically, it may as well look dynamic too.

    AJAX Patterns: Design Patterns for AJAX Usability

    I’ve been putting together some AJAX design patterns.

    Update (May 15, 2005): I’ve set up to keep working on these patterns. I’ve also cleaned up a couple of things here, although all future changes will occur at ajaxpatterns. Thanks to Leoglas for spotting two errors here.

    Why AJAX Design Patterns?

    AJAX holds a lot of promise for web usability, and the underlying technology has already delivered some stunning applications. But it’s no magic bullet. Careful design is always required, and it must be based specifically on the technology at hand. As AJAX emerges, we’re going to learn more about what sort of design works, and we’ll need ways of documenting this information and talking about it. Fortunately, the evolution of this particular technology will take place at a time when design patterns are well-entrenched in the industry, and design patterns are an excellent means of knowledge representation. Thus, it makes sense to begin cataloguing AJAX design patterns. These are some thoughts based on current examples and demo systems.

    Patterns being patterns, there’s not a lot of unseen information here. Patterns are just a concise way to represent the knowledge embodied in the many AJAX applications that are out there. The point is to discover best practices by investigating how developers have successfully traded off conflicting design principles. AJAX is all about usability, so the patterns focus particularly on delivering usability in the face of constraints, most notably: user capabilities and expectations, bandwidth limits, the stateless nature of HTTP, the complexity of Javascript.

    This is a work-in-progress. There should eventually be more patterns, more examples, more detailed explanations. And one more disclaimer: AJAX is a new term, but XMLHttpRequest and related technologies have been around for a while. I know that, but the introduction of a single umbrella term nevertheless constitutes a tipping point which is forcing web development to move heavily in a certain direction. AJAX is only a name, but names can be tremendously important.

    Related Work

    • Thomas Baekdal’s AJAX Usability Guidelines contains some great advice and inspired me to write these patterns. What I’m doing here is not just stating different guidelines. Patterns ain’t principles, and the focus here is on patterns whereas the focus above is on principles. Both forms of design advice are vital. Here, I’m explicitly distinguishing between the two, because the patterns are intended to help designers achieve the principles. The principles here are heavily influenced by Baekdal’s guidelines.

    • and AJAX Matters contain great collections of AJAX examples. You can’t have patterns without examples.

    • Joel Webber illuminates the technology behind Google Maps. Chris Justus dissects Google Suggest.

    • The recent AJAX podcast and blog entry covered some of the strengths and weaknesses of AJAX. The patterns here are supposed to guide on emphasising the strengths of AJAX without being struck by its weaknesses. The Polymorphic Podcast has also covered AJAX – prior to my podcast and is recommended as alternative overview on the technology.

    Design Principles for AJAX Applications

    • Minimise traffic between browser and server so that the user feels the application is responsive.
    • Be clear on the interaction mode being used – regular HTML versus AJAX versus desktop application so that the user can predict what will happen next .. no surprises.
    • While avoiding confusion, borrow from conventions of HTML and desktop applications so that the user can rapidly learn how to use your application.
    • Avoid distractions such as gratuitous animations so that the user can focus on the task at hand.
    • Stick with AJAX wherever possible – just say no to entire page downloads so that the user’s experience is consistent.
    • Adopt AJAX for usability, not just to illustrate you’re hip to where it’s at so that the user is engaged, and not immediately driven away by your nod to website splash screens, <blink tags>, popup ads, and other usability disasters of websites which have gone to a place you don’t want to be.

    Some (and eventually all?) of these principles above inform the patterns below. The patterns are about trading off among the principles, and also about resolving conflict between the needs of usability and other practical constraints, such as ease-of-development.

    Architectural Patterns

    Local Event-Handling You want the user experience to be dynamic and responsive, but it slows things down if you have to keep going to the server. THEREFORE, ensure most events are handled locally, resorting to server-side interaction only when there is no local facility. To increase the cases where local handling is sufficient, consider using Local Caches.

    Local Cache You want to support Local Activity, but many events must be handled by resorting to data on the server. THEREFORE, maintain a local cache of information. The cache might be created on initialisation or accumulated after each query. When accumulating upon query, it’s probably worthwhile performing a predictive download.

    • Example: Websites have kept local information at hand for many years. Many forms cache a mapping from countries to states, for instance.

    Predictive Download You want the application to respond quickly, but many user actions will require information from the server. THEREFORE, anticipate likely user actions and pre-load the required data. Note that this auxiliary information should ideally be downloaded after the main information has been loaded. A “background thread” might even be used to continuously monitor the user’s local behaviour, regularly pulling down information which might be useful.

    • Example: Google Maps downloads more than you ask, evidenced by the fact that you can move a little in each direction without forcing any new blocks to be loaded. Another way to see this is to compare what happens when you pan slowly versus quickly. Another example is International Herald Tribune, which caches entire articles to provide immediate gratification when you click on “next page” (an example taken from here. Google asks the browser to prefetch the first search result in case the user clicks on it.

    Submission Throttling You want the application to respond quickly, but it will be overloaded if the server was accessed for every trivial input event. THEREFORE, instead of submitting upon each Javascript event, use the events to change local state. Store events in a buffer variable, or some DOM component, and frequently (e.g. once a second) poll to see if anything should be submitted. As a variant to periodic polling, check the time since last submission whenever a new Javascript event occurs. Note: If the period is long (e.g. 10 minutes), show the Synchronisation Status and consider allowing explicit submission as well.

    Explicit Submission (An alternative to Submit Throttling.) You want the application to respond quickly, but it will be overloaded if the server was accessed for every trivial input event. THEREFORE, instead of submitting upon each Javascript event, require the user to explicitly request it, e.g. submit upom clicking a button. Ensure the user knows what’s been submitted with Synchronisation Status.

    • Example: Like many chat applications, the LiveChat demo requires you to click a “submit” button in order to complete your chat message.

    Periodic Refresh You want the browser to be synchronised with the server, but information may change server-side after the user last made a change (e.g. because of another user on the same system). THEREFORE, the browser should periodically call the server so as to refresh any volatile information. Furthermore, indicate information staleness is with Age Displays.

    • Example: Open two browsers, and you’ll see that this chat demo polls the server for changes every few seconds.

    Distinct URLs You want to let users send and bookmark information, but the application is dynamic and the results of XMLHttpRequest interaction will not alter the URL. THEREFORE, use a URL-based scheme or write distinct URLs whenever the input will cause a fresh new browser state, one that does not depend on previous interaction.

    • Example: A9 interacts via AJAX, but nevertheless provides a clean URL when you perform a new search. Google Maps has a “Link to this Page” link, which will always provide a link to whatever the user is looking at.

    Display Patterns

    Rich CSS You want the user-interface to be rich and colourful, but you have to minimise download size in order to make the interface responsive. THEREFORE, lean heavily on CSS to give a rich, graphical, appearance, without having to download images.

    Embedded Text You want the-user interface to be rich and graphical, but you need plain text in order to support standard web functionality such as cut-and-paste and inspection by search engine robots. THEREFORE,integrate text into graphics, and rely on Rich CSS to show text when fancy styling is desirable.

    Age Display You want the user to trust the system, but it’s possible some information on the browser is stale. THEREFORE, indicate the age of any critical information. Vary background brightness, for instance.

    • Example: SkyScanner is a non-AJAX price comparison site which shows how old its prices are. Many trading applications do likewise with stock quotes. I’m not aware of any AJAX examples at this stage; this pattern is purely speculative and likely to be relevant only to public websites which cannot justify frequent updates.

    Synchronisation Status You want the user to rely on the system to capture the input, but not all input is immediately submitted because you are using Submit Throttling or Explicit Submission. THEREFORE, provide hints that indicate what’s synchronised and what’s pending. For instance, use a different background colour on text fields. This is important if you are using Explicit Submission or Throttling with a long period.

    • Example: Manoloweb’s wiki-like demo tells you when the edit has been submitted (although is possibly buggy as the message is always there?). (Note: Since web forms were born, many heads and fists have been banged against keyboards after information was lost to timeouts and shutdowns. AJAX is capable of solving this problem, and this pattern is part of the solution.)

    Interaction Patterns

    Nothing new here. All have been available in desktop GUIs and some in non-AJAX DHTML too. This is really just a catalogue of interaction styles that are becoming common idioms in AJAX applications and can benefit from XMLHttpRequest-driven interaction.

    Drag-and-drop e.g. This demo

    Popup data input

    Popup information

    Highlighting e.g. A9’s customisation feature highlights search plugins you select them.

    Drilldown e.g. Betfair’s Sidebar Menu.

    Auto-Completion Most famously, Google Suggest.

    Coding Patterns

    Browser-Agnostic Components You want to make the system interactive with sophisticated DHTML, but portability can suffer. THEREFORE, encapsulate units of DHTML activity into browser-agnostic components. A “component” may simply be a Javascript function with a bunch of if-statements, or a factory in an Abstract Factory hierarchy, or a server-side, Javascript generation object.

    Server-Side Code Generation You want to make the system interactive with sophisticated DHTML, but sophisticated DHTML can be difficult. THEREFORE, use a server-side framework to generate the HTML and associated Javascript. Note that this pattern will become more useful as frameworks emerge.

    Further Issues

    … which will emerge as patterns.

    • RESTful architecture and treating server requests as API calls. There’s a lot of scope for XMLHttpRequest to be dealing with a generic, public, API. For instance, it didn’t take long before Google Maps had been recruited as a geographical API.
    • The “X” in AJAX. How should the response be structured?
    • Collaborative applications. How to deal with merges, pessimistic/optimistic locking, etc.

    Your Thoughts?

    I’m interested to hear what people think. Leave a comment or send an email to [email protected]

    Advanced Javascript Book: Professional JavaScript for Web Developers

    Not your grandfather’s Javascript … looks like Nicholas Zakas’s Professional JavaScript for Web Developers is now out. This is great news, as the book’s editor – Jim – noted that there’s an AJAX chapter in there. Well, he, qualifies, “OK, not exactly. What he wrote for that book is chapter 16 “Client-Server Communication” (see the full TOC here) which is all about AJAX principles without actually using that term not coined until a couple of months ago.”

    I’m about to order it and looking forward to it. With AJAX coming on strong, Javascript will only get bigger and bigger. So it’s time for the eternal optimists to swallow the pill and learn how to do it the right way. This book will do well: advanced Javascript texts are rare, and, as far as I can see, nothing has been published for several years. Given all the recent browser updates, that alone is enough reason to get hold of it.

    BTW, there’s been a great response to the AJAX podcast in the past couple of weeks. I’ll mention more in my next podcast, but for now, one thing’s pretty clear: by the end of the year, AJAX is confirmed as the buzzword of ’05.

    Self-Documenting is Self-Reinforcing

    I just discovered James Shore’s blog. Lots of interesting stuff around agile development. In particular, his post, “Down With Comments”. It refers to a recent slashdot article on comments in code: Comments are More Important than Code. As a guy who’s keen on self-documenting software, I have to say that’s a rather provocative title.

    Interesting, too, that many posters bought into the argument.

    There are two sides to this debate, along with the obligatory hand-waving qualifications. In my experience, it often comes down to experience. As Alistair Cockburn has pointed out, methodologies are created due to fear, and fear comes from experiences. In the same way, people who favour lots of comments have often worked with cruddy code and in reactive environments where there is no inclination to improve the situation. No wonder they fear raw code. That most people have this experience should be evident from the fact that most environments, sadly, do actually work this way.

    As with many aspects of software development, there is a self-reinforcing feedback loop. In one universe, you can choose mediocre coding, not much refactoring, and lots of instructive comments. Maintaining the instructions will take a lot of time up, so no further refactoring. With a shrug of the shoulders and a slightly guilty, “it’s explained in the Javadoc”, the instructions will be used to justify broken code. Self-propagating. Meanwhile, in another universe, a conscious decision will have been made to strive for self-documenting code wherever possible. Some comments are justifiable, but they must earn their place: they are guilty until proven innocent, and can’t just be slapped on to cover up fundamental coding flaws. In this universe, the code will benefit from well-considered terminology, consistency of conventions, architectural coherence. The process will support it too: tests will help alleviate the need for documentation while supporting refactoring, and the refactoring effort will be used to wipe out suspect comments. All code will be treated as living – developers will understand it, be on top of it, and, being humans, share the knowledge. Alistair Cockburn comes to mind again: human conversation is much more effective than reading, and that includes reading comments.

    HCI practitioners decided a long time ago that applications should work out of the box, because no-one reads instruction manuals anyway. People learn by doing and talking to others. Should software be any different?

    XP Explained: Changes in 2nd Edition?

    The 2nd edition of Extreme Programming Explained has been out for a little while now and Darrell Norton has been covering it in a three-part series. What I want to know is, what’s changed since the first edition? It would be extremely (yes but it’s the right word here) valuable to know exactly what’s been changed and why. I know that the practice of metaphor has been dropped. Other than that, information to that effect is scant.

    Any takers?

    Fancy Input in IDEs

    There’s been a lot of talk about viewing code in fancy ways. For instance, James Gosling’s work on Jackpot.

    Well, how about fancy input as well?

    Some ideas from the world of HCI:

    • Speech input: Speech is a great way to switch modes and perform simple tasks, without lifting your hands off the keyboard and without moving the mouse back and forth. I would respect an IDE that let me utter such commands as “Build” and “Test”, and such mode switches as “Debugger” and “SampleInput.xml”. This isn’t intelligent human-robot relations; just simple commands to stupid routines. Easy enough in 2005, even with background noise and diverse accents.

    • Drag-and-drop: Since the source is now a structured object for the purposes of refactoring and syntax highlighting, let me manipulate it as such. Much as a Lisp program might do. For instance, I should be able to drag a class from the package view into a source file, which would create a new instance variable. Or I could pick up a method in the source file and drag it into another class in the package view.

    • Source-Based Refactoring: We already have the lightbulb-based “intents”, which suggest code changes based on the current state. However, that’s only based on the static state of the code: the sequence of characters as it currently stands. How about looking at what the programmer’s actually doing. Oh-oh, this is getting into “Hi I’m Annoying, you seem to be writing a letter. Would you like me to ‘help’ you?”. Well, just because an idea was poorly executed doesn’t mean it can’t work. For instance, you should be able to perform a “Change Signature” refactoring by … changing the signature! Directly. Not by opening up a “Change Signature” dialog box, which involves a distracting jump to a new level of abstraction and a completely different interaction paradigm. But by simply moving some text around. If the IDE detects you’ve done that, it could automatically – oh, and unintrusively – suggest a Change Signature refactoring. Most refactorings I can think of could be detected by watching the user change the source directly. Deleting text or pulling a member up, for instance. You could extract a method by selecting the entire code block and then replacing it by simply typing the method name.

    These thoughts are only based on novel input with today’s technology. It will get a lot better than that as we learn about how future rendering algorithms best interact with future input mechanisms.