Wednesday, August 10, 2011

This Side Up? When Mobile Web Pages Rotate

So I spent a little time this last week working on my "mini mobile CV." It's targeted at mobile devices and was intended originally to demonstrate that I knew how to properly select easy to read fonts and high contrast color schemes for constrained hardware. But as I got into it and saw my device automatically rotate from landscape to portrait mode, I got curious. "What is the best way to detect an orientation change on a mobile device?"

Being familiar with "dark ages" web programming, I originally assumed the solution would involve a fair amount of hackery, reading the heights and widths of transparent divs and so forth. But fortunately, it's not hard at all. Despite recent W3C efforts to define a standard DeviceOrientation Event Specification, it seems many Android devices in the field are copying Apple's Mobile Safari behavior.

You probably want to start by figuring out if the device rendering the page will be generating orientation change events. Do this with the following code snippet:

var supportsOrientation = ( "onorientationchange" in window );

This line checks to see if the 'onorientationchange' property is set in the window object. If it is, then your browser should generate orientationchange events. Next, we want to add an event listener, like so:

if( supportsOrientation ) {
window.addEventListener( "orientationchange", function () { console.log('w00t'); }, false );
}

Of course, printing out a debugging message to the console every time there's an orientation change is vaguely useless, so we may want to consider something beefier. When the orientationEvent fires, you'll want to read window.orientation to find out how many degrees the device has been rotated. But be careful, on some devices, you'll get a shower of these events even though you've only rotated your device once. It's good practice to remember the last orientation value and only "do something" when the orientation actually changes.

var previousOrientation;

function checkOrientation () {
if( previousOrientation !== window.orientation ) {
previousOrientation = window.orientation;
// do interesting things here
}
}

So, putting it all together and adding a bit of callback convenience, you get something like this:

function Rotor ( callback ) {
this.callback = callback;
if( "onorientationchange" in window ) {
this.previous = window.orientation;
callback( this.previous, null );
window.addEventListener( "orientationchange", this, false );
}
}

Rotor.prototype.handleEvent = function ( e ) {
var current = window.orientation;
if( current !== this.previous ) {
this.callback( current, e );
}
this.previous = current;
};

To use it, just instantiate a new Rotor, giving it a callback that knows what to do when the device is rotated.

var roton = new Rotor( function( rotation, event ) { alert( 'current rotation: ' + rotation ); } );

Cheers!

Wednesday, July 20, 2011

strange programmer habits : number and string mutation

Some of my favorite programming languages allow you to be "fast and loose" with data types. JavaScript and PHP, for instance, will convert variables between number and string types as needed. Some consider this behavior to be "sub-optimal," while others don't. But understanding how your programming language converts literals or variables between types is important, no matter what language you're using.

Consider the following C program:
#include <stdio.h>
int main( int argc, char *argv[] ) {
  char *start = "1234";
  int a = 2;
  printf( "%s\n", (start + a ) );
}
When you compile and run this program, it prints out the string "34" and then exits. Now look at this JavaScript function:
function foo() {
  var start = "1234";
  var a = 2;
  console.log( start + a );
}
It should print out the string "12342". Understanding why C does one thing and JavaScript does another is important. C aficionados can probably quickly point out that the printf() function was taking a pointer to an array of characters as it's input. Adding the integer 2 to the pointer caused it to point 2 bytes ahead. When interpreted as a string, "(start + a)" is simply a two byte string with the value "34".

JavaScript, on the other hand, converts the number 2 into the string '2' and appends it to the string.

Doing the same thing in PHP yields even different results. Executing the following PHP fragment will cause the system to print the string "1236":
$start = "1234";
$a = 2;
echo ( $start + $a )
PHP peeks inside the variable $start, sees that it looks like a number and then converts it to an integer and performs the addition.

JavaScript provides a functions to convert numbers to strings and vice versa. The "String( val )" function attempts to convert the argument 'val' to a string while the "Number( val )" function attempts to convert 'val' to a number. People went to the trouble of specifying these functions and documenting them, so you might as well use them.

Some people, their minds perhaps addled by exposure to early versions of PHP have been seen to do things like this in javascript:
var a = 12;
console.log( "" + a );
or
var b = '34';
console.log( 1 * b );
Adding an empty string to a number in JavaScript will (should) cause the interpreter to convert the value of a into a string. Multiplying the string b by one should do the opposite (convert the string into a number.)

Some people believe this type of conversion is faster, others think it's just plain ugly. It is certainly the case that "standard" functions exist to do the same thing, and might convey the programmer's intent more clearly.

It's up to you, of course, which technique you use to coerce a value to a particular type, but if you inherit code with superfluous additions and multiplication, this might be what's going on.

Wednesday, July 13, 2011

strange programmer habits : avoiding goto's by using do..while's

In the early days of computer software, programmers were using languages like assembly, fortran, cobol and lisp to produce reasonably small programs to compute trajectories, maintain inventory databases or accounting systems and whatnot. Computing systems weren't big enough to allow programmers to make the massive software systems like modern operating systems, web browsers or computer games.

This is probably why it took a couple decades for people to understand how bad "spaghetti code" was; it's easy to dismiss spaghetti being a problem when your complete software system is one or two pages long. But when a printout of your system requires you to chop down a medium sized forest, concepts like "structured programming" and "design patterns" really start to become important.

One of the popular issues around the programmer's water-cooler in the 1980's was whether or not people who use goto's should have their fingers chopped off. Edsger Djikstra penned the canonical software engineering jeremiad about this subject entitled “go-to statement considered harmful” [PDF]. You can probably guess his opinion from the paper's title.

So in the 80's and 90's, software engineers were taught that goto's led to un-maintainable software, headaches and all manner of social ills ranging from global warming to bad movies to disco. "Use a goto," they would say, "and it's like asking the local DJ to play Disco Duck on the radio." Structured programming, good software engineering technique and eschewing goto's would lead to a new era of increasingly good Cure albums, Alien sequels that didn't suck and fewer evenings in the office at midnight debugging the crap code you wrote last year.

But, like the one true ring, the expressive power of the goto is difficult to resist. Many software wizards, on their way to a life of perdition (i.e. - writing video games) countered that the goto could be used on occasion, if done correctly. Consider the following routine; it tries to open a file and read a few bytes. If there are errors along the way, it uses a goto to branch to clean-up routine before exiting:
int doSomething( char *filename ) { int err = 0; FILE *file = (FILE *) NULL; char buffer[ 80 ]; size_t bytesRead = 0; if( NULL == filename ) { err = -1; goto exuent_omnis; } if( (FILE *)NULL == ( file = fopen( filename, “r” ) ) ) { err = errno; goto exuent_omnis; } bytesRead = fread( buffer, 80, 1, file ); if( ferror( file ) ) { err = -2; goto exuent_omnis; } /* more code here */ exuent_omnis: if( (FILE *) NULL != file ) { fclose( file ); } return( err ); }
"What could be wrong with this?" the pro-goto lobby would ask. IMHO, this example is pretty readable, and the goto DOES actually increase readability. Especially if you consider that nested if's are frequently offered as the alternative:
int doSomething( char *filename ) { int err = 0; FILE *file = (FILE *) NULL; char buffer[ 80 ]; size_t bytesRead = 0; if( NULL != filename ) { if( (FILE *)NULL != ( file = fopen( filename, “r” ) ) ) { bytesRead = fread( buffer, 80, 1, file ); if( ! ferror( file ) ) { /* more code here */ } else { err = -2; break; } fclose( file ): } else { err = errno; } } else { err = -1; } return( err ); }
People who propose extensive use of nested if's should have their thumbs broken. This example isn't that bad, but when nested ifs start spanning pages, they can get a bit difficult to read. The alternative to using gotos in this example would be to use a do...while() loop whose repeat condition has been explicitly set to zero (or false for C++ users.):
int doSomething( char *filename ) { int err = 0; char buffer[ 80 ]; size_t bytesRead = 0; do { if( NULL == filename ) { err = -1; break; } if( (FILE *)NULL == ( file = fopen( filename, “r” ) ) ) { err = errno; break; } bytesRead = fread( buffer, 80, 1, file ); if( ferror( file ) ) { err = -2; break; } /* more code here */ } while( 0 ); if( (FILE *) NULL != file ) { fclose( file ); } return( err ); }
Developers who like this kind of code will tell you it captures the succinct directness of a goto without actually having a goto. Because we break out of the loop, there's only one place control can go: to the statement after the while( 0 ); And we avoid nested if's. I've encountered at least one developer who believes this technique is harmful; it uses the do...while language feature for something it was not intended for, and as such, could be confusing to younger programmers.

Whether you make Djikstra cry by using a goto, produce deep levels of indents or use a do...while(0) that's confusing to in-expert programmers; it's entirely up to you. But hopefully this article will have made you aware of the different techniques you'll encounter in the wild.

-Cheers!

Wednesday, July 6, 2011

strange programmer habits : commas at the beginning of lines

So, consider this C program:
#include <stdio.h> char *verbs[] = { "quit" , "score" , "inventory" , "go" , "get" , NULL }; int main() { int i; for( i = 0; verbs[ i ] != NULL; i++ ) { printf( "verb %02d: %s\n", i, verbs[ i ] ); } }
or it's javascript equivalent::
var verbs = [ "quit" , "score" , "inventory" , "go" , "get" ]; for( var i = 0, il = verbs.length; i < il; i++ ) { console.log( "verb " + i + ": " + verbs[ i ] ) }
Both these programs declare an array of strings and then print them out. But contrary to popular convention, the commas separating individual elements of the verbs array come not at the end of the line, but at the beginning.

The compiler (or interpreter) couldn't care less about this stylistic convention, of course. All it cares about is if there are commas between array elements. The comma-first style is there to make it easier for you to add, delete or move single lines in the array. By putting the comma at the beginning of the line, you move the elements in the array around without having to manually add (or remove) a trailing comma at the end of the array.

This strange habit doesn't effect the output your compiler produces and it's main benefit is to save a couple milliseconds when cutting and pasting entries in an array. But a small number of programmers (myself included) have gotten used to seeing arrays that look like this, so don't be surprised if you see this style from time to time.

Wednesday, June 29, 2011

strange programmer habits : literal comes first in a comparison

Consider this JavaScript code:
function foo( aString ) { if( ‘:error’ == aString ) { handleError(); } }
Why put the variable reference after the string literal? So you don't accidentally turn the comparison into an assignment. Look at this code:
function foo( aString ) { if( aString = ‘:error’ ) { handleError(); } }
Do you see the error? The programmer has accidentally dropped one of the equal signs in the comparison operator. If this code was being edited at 4AM the day before a big demo, believe me, it would be hard to spot.
But if put the literal was first and then forgot the extra equals sign, we would get an error. Go ahead and try it. Open up the javascript debugger in your browser and copy this code fragment into it:
( function ( aString ) { if( ‘:error’ = aString ) { console.log( ‘looks like we were passed an error token.’ ); } } ) ( ‘blarg’ );
You should get a syntax error, which should clue you off that you forgot an equals sign. This is a programmer habit seen in most "curley brace" languages (C, C++, Java, Python, etc.) JavaScript programmers may also want to consider using the "strict equal" comparison operator (i.e. the triple equals.) Refer to Mozilla's excellent Javascript Docs for more info.

Tuesday, June 21, 2011

chromium os on a dell mini 9? i like it

so for the last week i've been playing with chromium os. it's the linux-based web-focused operating system from google everyone's been yammering about for the past week. samsung and acer just released a couple "chromebooks," and it seems like the tech press is falling over itself to pan the devices. but i recently took the plunge and installed chromium on my dell vostro a90 (aka mini 9) and here are my impressions.

i like it. (with some caveats)

let me start by saying i'm a bit of a google fangrrl; not a complete fangrrl, but a fangrrl nonetheless. i started taking google services seriously several years ago when i subscribed to gmail. i love it: all my mail is available from any PC i happen to be sitting in front of. i was also an early adopter of writely (later google docs.) i love it for exactly the same reason: my documents automatically follow me around from machine to machine.

so i'm not a google fangrrl in the same way that people can be apple fans. design is important to me, but i'm more interested in the program's interface and capabilities. sure, cool looking hardware is nice, but it's the UX that counts. google's UI for gmail, gdocs, &c aren't "beautiful" in the way that apple interfaces are beautiful; but they're more than good enough. i am also not so much of a google fan that i use google buzz or wave or orkut.

i've been burned by syncing too many times in the past to trust anyone to get it right. i like the google services because they give me document and service mobility without having to think about it. that is my primary consideration.

yes, i occasionally happen to have my netbook powered on when there's no network coverage. and that sucks. for me, the benefits of service mobility outweigh the drawbacks of not being able to get to my docs when the network evaporates.

so i'm sure you've heard of gmail and google docs and picasa. i use them. they're great. however, there are a couple other services you might not have heard about. (and it's okay, these are all pretty much services for software developers.)

one service i kind of had to start using is Cloud9. it's a javascript editor and development environment right in your web browser. it's not perfect, but with the recent git and mercurial integration, Cloud9 is the node.js developer's equivalent of an unstoppable force whose kung fu will defeat the forces of evil. okay. maybe it only seems that way 'cause i'm a fan of storing your stuff in the cloud. but check it out. when my free trial expires, i'm totally giving them the small amount of money they're asking for. your mileage may vary.

in the future, i hope the Cloud9 team convert my money into a group editing / etherpad-esque feature.

so that's basically been my week. i installed chromium on my dell (thanks to the work by Doug Anson of Dell's CTO's Office.) i continued using google services i have been using, and started using (and was impressed by) Cloud9.

and i think the future is going to be even brighter. google docs currently have the problem that they don't make use of HTML5's local storage and web application APIs to provide a compelling "offline experience." (gmail currently has an "offline mode.") but CNET (and others) are reporting that we'll start seeing offline editing features this summer. if/when this happens, one of the largest complaints people have about chromebooks will disappear.

so... chromium on the dell mini-9 is a great alternative to paying $500 for a new laptop; especially if, like me, you happen to have a mini-9 hanging around the house. installing the OS was pretty straight-forward; use the link to Doug Anson's build above; hexxeh flow had some problems loading on my mini-9. but even Doug's work has a few warts:
  1. there's no audio - this is a known problem. Doug says it'll likely get fixed in a future release.
  2. there's no (easy) java - the most recent dell build of chromium doesn't ship with java, and the stock java installer for linux barfs (i'm guessing because of unfulfilled dynamic libraries.) i didn't spend a lot of time on getting it to work, and have seen java work on other chromium builds, so i know it can be done. it's just not easy.
  3. wifi's turned off out of the box - like many linux devices that use broadcom wifi chipsets, you have to download the proprietary drivers using a wired ethernet connection before you can experience wireless bliss. but it's pretty straight-forward to add the drivers. the release notes intimate the dell guys are working with the broadcom lawyers to figure out a way to include the drivers in the stock build, so maybe this problem will go away.
  4. WebGL? if it's enabled in the may 13th build, i've yet to see it work.
so, chromium os on a dell mini 9: i like it. it's not without it's warts, but it's a better alternative than plunking down $500 on a new laptop.

Monday, June 6, 2011

a few new node modules

people who know me know that i love node.js, the javascript network application framework. most of the projects i've prototyped in the last couple of years have been done with javascript in a browser and node.js on the server. i don't know why it took me so long to think about this, but i'm finally releasing some of the tools i developed. (okay, technically, i re-implemented them to avoid some project specific kruft.)

but anyway, in the last couple of weeks i released two node packages: node-props and node-mug.

node-props.js

node-props is a package that lets developers read properties from one or more URIs specified on the command line. so, basically, you can do this:
node application.js --config file:///etc/host_props.json --config https://example.org/app_props.js
i found the ability to grab properties from multiple locations is good for "cloud-like" applications. i use it to separate "host config" parameters (e.g. - addresses & ports to listen on) from "application config" parameters (like db addresses, etc.)

separating the two classes of config info provides a bit of flexibility if you're deploying an array of servers. by placing application config information on a central server, you only need to change a single file to change your app's behavior.

the package has been published to the npm registry and the source is available at https://github.com/OhMeadhbh/node-props

node-mug.js

the node-mug package exports an interface developers can use to generate RFC 4122 compliant Version 4 (random) UUIDs. unlike some other UUID generators for node, node-mug collects entropy from the /dev/urandom file present on most modern *nix systems. paranoid app developers can configure the system to read entropy from /dev/random.

interested users can install node-mug via npm or retrieving the source from the git repository at https://github.com/OhMeadhbh/node-mug

happy coding!