Tag Archives: JavaScript

A tour of the differences between JavaScript and Python

Introduction

JavaScript and Python are two very important languages today. Too many programmers, however, work in both languages, but know just one of them well. This means they end up writing code in one language in the same style as the other, unaware of some of the more subtle differences between the two. If you know JavaScript or Python well, and you want to improve your skills and knowledge of the other, I wrote this article for you.

Disclaimer: I know Python (slightly) better than I know JavaScript, and I’ve not done any JavaScript outside of the browser, so I tried to keep the bits about JavaScript agnostic to the host environment, but, fair warning, there may be subtle differences in server-side JavaScript that are not mentioned here because I don’t know them.

Continue reading

Two new projects: German Grammar and Möbius

I’ve been hacking on two new projects in my spare time.

The German Grammar Explorer (mainly the German Declension Explorer) is helping me wrap my head around some of the more complex patterns in the German language. It’s also an experiment in deliberate synæsthesia; It uses a palette of eight colors plus white to color-code similar patterns and related morphosyntax. The idea is to give a general feeling for when the general patterns of the language are broken.

Möbius is a totally useless experiment in binding scroll events and doing funny stuff with them, and experimenting with some newer features of HTML 5 and CSS 3.

Grasping the nuclear fourth rail of Python syntax with both hands and holding on for dear life

In Python vs. Ruby: A Battle to The DeathGary Bernhardt wishes for Ruby-style blocks in Python.

The BDFL has already weighed in on anonymous blocks in Python:

If you want anonymous blocks, by all means use Ruby. Python has first-class callables,1 Ruby has anonymous blocks. Pick your favorite, but don’t whine that neither language has both. It ain’t gonna happen.

This seems to imply that first-class callables and anonymous blocks are mutually exclusive language features, but that’s wrong: JavaScript has the ability to pass callables around like anything else, and it has anonymous functions, which can be used just like Ruby’s anonymous blocks. Does that mean JavaScript is better than Python or Ruby? My feelings about Ruby are indifferent with a chance of rain, but I love Python, so I’ve got to ask: are you going to take this lying down, Python?

I’m not sure Python needs full-blown, Ruby-style anonymous blocks. But it might be good enough to be able to use function definitions as r-values, like JavaScript can. (If you’re not already wearing your tinfoil hat, now might be a good time to put it on.)

This would allow asynchronous code to be written in conceptual order (just like in JavaScript):

do_something_asynchronous(param1, param2, (def callback(result):
    do_something_with_result(result)
))

And it would allow encapsulation of lexical scope inside specific iterations of a loop to be used later when an asynchronous call returns (just like in JavaScript):

for item in results:
    (def single_iteration():
        do_something_asynchronous(param1, item, (def callback(result):
            do_something_with_result_and_item(item, result)
        ))
    )(item)

I’ve even had occasion to want that other Python namespace, class, to operate as an r-value:

class MyConverterClass(BaseConverterClass):
    my_converter_type = (class MyConverterType(float):
        def __str__(self): # a custom __str__ method
            return '%0.2f' % self
    )

In these examples I’ve wrapped their inline definitions in Python’s great syntactical equalizer, the parenthesis. It would be even nicer to be able to leave them off, but I’m sure that this syntax would run headlong into Python’s whitespace-based block definitions, and it would be even more of a train-wreck without parentheses.

I’ve also named the defs and classes. It would also be nice to be able to omit the function or class names if they were unneeded (just like in JavaScript). But anonymous functions, a.k.a. lambdas, are the electric third rail of Python syntax, so anonymous classes would be… I dunno, the nuclear fourth rail?

  1. Thanks to Steve for explaining that by “first-class callable,” GvR means functions that can be passed around and assigned to other variables without being executed. He also pointed out that the reason Ruby’s callables aren’t first-class is because optional parentheses in function calls leave no way to refer to a function without calling it, not because of the existence of anonymous blocks. []

Ten ways to build an unmaintainable web application

Old-school hackers had a long tradition of ensuring job security by building applications so unmaintainable that only the original authors could work on them. But in these days of web applications, unmaintainability has fallen by the wayside. Instead, design fads like CRUD, REST, MVC, DRY, and KISS, have eliminated the average programmer’s job security.

Here are ten quick tips for achieving maximum unmaintainability in your web application. Following them will ensure that, in thirty years, a web programmer like you will be as valuable as a fifty-eight year old COBOL programmer contracting at $200/hr for a Fortune 500 company that still hasn’t migrated off of PL/1. You too will be able to live on a dairy farm in Pennsylvania, grow a beard down to your navel, and work in your underwear. And you’ll never have to learn anything new, work with anyone else, or start another new project.

  1. Mix it up. Put some JavaScript into external files, but be sure to intersperse JavaScript into your HTML, some of it in <script> tags. Cram multiple JavaScript statements into onclick and other event attributes — the longer, the better. Do the same with CSS; put some into external files, some in <style> tags, and also put some critical CSS into complex style attributes. And remember to put most of your <script> and <style> tags in the middle of the page content, instead of in the <head>, so that they will be difficult to find.
  2. Make everything dynamic. Generate JavaScript and CSS in your HTML templates. Think of it as another type of eval. Generate HTML server-side using templates and browser-side using JavaScript. What’s harder than working around a obscure IE layout bug with weird markup tweaks? Making sure both your server templates and your JavaScript HTML generation work around the same bug with the same HTML black magic.
  3. Abstraction, Shmabstraction. Pass lots of data from the server to the browser, store it in hidden form fields in the page, and then pass it back, unchanged, when submitting the form. That way, when the back-end data model changes, you get to rewrite part of the interface too. Allow data-model or server implementation details to creep into the interface implementation. Is the database sharded? Is the cache dirty? Does this row use a composite key? No need to have the server abstract these details, just pass that information to the JavaScript and let it sort everything out. That way, a sysadmin or a DBA can break the UI just as easily as a web designer can.
  4. Keep your data unstructured. Make sure all communication between the browser and the server is just a flat list of key/value parameters. Some of your parameters will be data to store, others will be modes or flags that affect the behavior of the service you’re hitting, and still others will be modifiers to display messages or affect the behavior of the UI. Keeping your data unstructured ensures these different types of parameters will collide. Often.
  5. Commit to a platform. Don’t waste your time checking to see if your pages work in all browsers (at least not until you’re totally done). Better yet, develop only in a single browser and don’t even bother to find out whether the features you’re relying on even exist in other browsers. Nothing is more fragile than an application that’s tightly tied to a single platform.
  6. Trust the browser. Rely soley on JavaScript input checking for some data — don’t check input on the server-side. Store sensitive data in hidden form fields. Put authorization checks in the JavaScript rather than on the server. Parameters like authorized=1 just scream out for URL hacking, and storing them in hidden form fields is only slightly harder to hack.
  7. Trust the server. Rely soley on the server to check, store, and generate only valid data in some places. That way, a DBA can change a single column constraint or data-type, and parts of the UI start to fail.
  8. Don’t use DOCTYPEs. That way you’ll never be sure what rendering mode different browsers are going to use to render your content.
  9. Ignore the cascade. Don’t bother to understand what the C in CSS stands for.  Just keep overriding styles until a page element looks the way you want. That way, your styles will be fragile and will break unexpectedly when an intern changes something a reasonable person would expect to be unrelated.
  10. Don’t use classes or ids. Instead, always write JavaScript and CSS that finds nodes based on tag name, name, alt or title attributes, or by their position in the DOM. That way when anything in the page changes, the hierarchy, the attributes, or when the site is translated into another language, things break. If you do end up using class or id, be sure to make a separate class for every node in your document and assign the same id to several different nodes.

If, however, you want to write flexible code that can react to and evolve with the ever-changing needs of its users, even after you have left the project in the hands of a clever but inexperienced hacker, you should probably avoid these techniques, and read up on some of those lame new design fads instead.

Special thanks to all the programmers whose code has illuminated these techniques over the years. My job may not be as secure as yours, but at least my code, and my conscience, are clear.

A tiny fix to the jQuery hint plugin

Here’s a tiny fix to Remy Sharp‘s excellent jQuery Text box hints plug-in. Without this fix, jQuery‘s val function will return the hint text if the text box hasn’t been filled out by the user yet.

Here’s the patch:

@@ -20,7 +23,7 @@
       $win = $(window);

     function remove() {
-      if ($input.val() === title && $input.hasClass(blurClass)) {
+      if ($input.realval() === title && $input.hasClass(blurClass)) {
         $input.val('').removeClass(blurClass);
       }
     }
@@ -41,4 +44,17 @@
   });
 };

+
+$.fn.realval = $.fn.val;
+
+$.fn.val = function (value) {
+  var i = $(this);
+  if (value === undefined) {
+    return (i.realval() === i.attr('title')) ? '' : i.realval();
+  } else {
+    return i.realval(value);
+  }
+}
+
+
 })(jQuery);

And here’s the full plugin with the patch applied:

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*
* better val() method added by Matt Chisholm, 2009/07/27
* http://glyphobet.net/blog/essay/878
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) {
    blurClass = 'blur';
  }

  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),

    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.realval() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) {
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

$.fn.realval = $.fn.val;

$.fn.val = function (value) {
  var i = $(this);
  if (value === undefined) {
    return (i.realval() === i.attr('title')) ? '' : i.realval();
  } else {
    return i.realval(value);
  }
}

})(jQuery);

Visualizing the National Popular Vote plan

This graphic visualizes the progress of the National Popular Vote plan (more about the politics of this plan in Hacking the Constitution).

The existing visualization on National Popular Vote’s website was flawed enough to inspire this attempt at fixing it. They use a national map with states colored according to the plan’s progress. Using geographical visualization conflicts with the plan’s intention to make the states as entities less influential, and with the plan’s success depending on the number of electoral votes, not the geographical size or population of the states1. And even though the steps in passing the plan suggest a spectrum, the colors are seemingly random.

Plus NPV is a good cause that deserves more attention. And as a vocal Flash critic, I should put my money where my mouth is and implement a cross-browser, scalable, interactive, vector graphic to show that it can be done without Flash.

Visualizing complex data well is challenging, and this is no exception. The plan will likely be adopted slowly over many years, so the graphic must be designed to expand. The technology must also be future-proof; I don’t want to have to re-implement the graphic, convert it to a different format, or get access to future versions of software, or the operating systems that software must run on, just to keep supporting it. This pretty much rules out Flash and Sliverlight.

These constraints make SVG2 and JavaScript a good choice. SVG support is still nascent in Gecko and WebKit3 (and even Opera supports it), but the standard is pretty usable and I expect it to gain more adoption over time. All of the rendering code is in JavaScript. I’d put money on JavaScript interpreters remaining readily available ten years from now. I unfortunately have no ability (or desire, for that matter) to test this in IE with Adobe’s SVG plugin; if you try it, email me the results.

There are many different entities involved in the process: fifty states, each with two legislative bodies and a governor, and a total of 538 electoral votes; and many different events: passing the first body of a legislature, passing the second, bills passing the same body subsequent times, being signed into law, being vetoed, vetoes being overridden, and (hopefully never) laws being repealed.

The data comes from disparate sources; most comes from NPV’s website, but I had to search for the vetoes. The data is not just linear; it overlaps and interacts. A veto affects two of the charts but not the third, and a repeal would affect all three. The three charts have an order; a bill cannot pass both houses before it passes one, and cannot be signed into law before it passes both.

To include all this data, a visualization would either have to be interactive or poster-sized. This one is interactive; you can mouse over vertexes in the charts and get more information about the events they represent. You can quickly and easily find out:

  • The exact progress of NPV at any time since its introduction.
  • Who, what and where for any NPV-related event.
  • All NPV-related events that have occurred in any particular state.
  • How significant each state’s contribution to the electoral vote tally has been.
  • Firsts, lasts, largests and smallests.

As with many real-world data visualizations, unexpected patterns emerge. Most activity is clustered in the winter, spring and early summer, when legislative bodies are in session. The only things that happen between August and December are vetoes. This cycle will likely become much more obvious once the graphic spans a few more years.

Hawaii’s legislature overrode their governor’s second veto, and The Governator has twice robbed the plan of California’s 55 electoral votes. Neither of these facts is obvious from the current graphic. If the plan is ever repealed, the graphic would need to show that too.

As I said in Hacking the Constitution, the the National Popular Vote plan deserves a lot more attention and support, so forward this page or NPV’s website to your friends, bring it up at parties, support it with a donation, or include the graphic on your web page.

  1. If a geographical design were used on a visualization of the progress of this plan, it should at least be a cartogram. []
  2. The HTML <canvas> element might also have been a viable option, but I already knew SVG. []
  3. For a good time, try resizing the font in Safari 3. []