Wednesday, November 16, 2011

loggin'

Yesterday I mentioned the importance of "log-based debugging". It's crucial to browser-based work, in part because alert()s and stepping through with the debugger mess up the timing of stuff, so they're not as much help for timing-related issues. I also think the act of putting in log statements forces a programmer to challenge their assumptions.

For reasons that are obscure to me, at work we call our main debug function "ccdebug". Its code is like this:

function ccdebug(s) {
  if (typeof console != "undefined" && typeof console.log != "undefined") {
    console.log(s);
  } 
}

Pretty simple! The check for console existing is necessary for preventing errors when the console isn't around...

I've been using that for just under 100% of my log statements... poking around I realize we have equivalents for console.warn() and console.error(). In firebug, the former has a nice yellow highlight, and the latter even includes a stack trace. So to improve my practice, I should probably start differentiating my information and coding messages from messages for more serious problems.

One other function I find useful, with both console.log() and good old alert():

function inspect(thing, indent){
if(indent == undefined || indent == true){
return JSON.stringify(thing, undefined," ");
}
return  JSON.stringify(thing);
}
That's just a great way to see the content of data structures and what not. The indent makes it a lot more readable, so I include it as the default.

Tuesday, November 15, 2011

simplicity simplicity simplicity -- shouldn't that just be 'simplicity'?

The other day I was thinking of Richard Gabriel's classic The Rise of 'Worse is Better'. The article has a kind of old context, but I think its core is still valid. (I also appreciate the vacillation within the article; these are issues about style and mood where there won't be a single correct answer.)

As the Wikipedia Page reiterates, the core components of "Worse is Better" are, in roughly descending order:
Simplicity
The design must be simple, both in implementation and interface. It is more important for the implementation to be simple than the interface. Simplicity is the most important consideration in a design.
Correctness
The design must be correct in all observable aspects. It is slightly better to be simple than correct.
Consistency
The design must not be overly inconsistent. Consistency can be sacrificed for simplicity in some cases, but it is better to drop those parts of the design that deal with less common circumstances than to introduce either complexity or inconsistency in the implementation.
Completeness
The design must cover as many important situations as is practical. All reasonably expected cases should be covered. Completeness can be sacrificed in favor of any other quality. In fact, completeness must be sacrificed whenever implementation simplicity is jeopardized. Consistency can be sacrificed to achieve completeness if simplicity is retained; especially worthless is consistency of interface.
The essay goes on to explain why these factors can be crucial to a technology really taking off. (Also it talks about the "New Jersey approach" (princeton reference?) vs the "MIT approach", terms I am including here for my future grepping needs.)

I find a rough analogy in my professional life as a UI Engineer when it comes to the selection of toolkits. I had a miserable time with "Wicket" and its bizarro blend of delicate flower Java class/HTML pairs. (It was barely ok for light work, but god help you in having to learn this whole lifecycle flow if something went wrong or you wanted to make your own component.) These days I've been arguing sticking with basic jQuery rather than taking on some heavier duty toolset like YUI or jsMVC.

So I ask myself, am I just a stick-in-the-mud curmudgeon who hates to learn new stuff? That's at least partially true: I'm much more interested in what technology can empower me to build than in the tools themselves, so I'm only interested in new toolsets when they let me do something new or in a vastly easier way, not just something old in a slightly more concise way. But I think there's something deeper in my preference for light weight toolkits, more profound...

I've said "People and computers should be judged by what they do, not by what (you think) they are." No one cares how finely crafted the objects in your code are, they just want to know, does it do the job well, and have you set yourself up to do the next few, slightly different jobs well. When I'm debugging, it's because the system is DOING something wrong, and I need to correct that behavior. My tools are-- lo and behold-- a debugger! and thoughtful logging... (good old log-based debugging is a crucial tool. I say that's because it forces you to think about what your preconceptions are at each step of the way, and then show them in action. But there's a chance it might also be because the debugging tools I used in college were so awful and opaque. Also, debuggers mess with the timing of stuff.)

Anyway, when I'm debugging, in a debugger, if I'm mostly looking at other's people code in the stacktrace, my job is much, much tougher. Most toolkits are extremely configuration heavy. (Toolkits by their nature don't just solve YOUR problem, but a hundred other problems as well, so you have to specify lots of things) It takes a fair amount of expertise and learning to set them up right, which costs time-- time you often don't have, the whole reason you're using the toolkit is for it to quickly solve your issue-- and when things break, there's often a huge gap between the misbehaving code and your error. The lighter the toolkit, the more likely the mistake is near where the debugger is showing the problem, the nearer the observed effect is from the code that caused it.

JQuery, I hardly ever have super tough to understand problems with. The few times the issue shows up in "jquery.min.js" itself, its been where I'm setting some property IE thinks should be read only or some such. Other tools I used, like Java RichFaces, the situation was much, much hairier. But with basic Javascript calling jQuery when needed, I can get to the problematic code easily.

Now this argument could be taken to an illogical extreme. I'm not saying you should code in assembly or anything like that... but your toolkits should be simple, reliable, and your widgets and libraries should be of the do one (hopefully difficult) thing and do it well.

(Of course, someone pointed out another reason to hate toolkits is they put a coating over the 90% of coding that is easy and pleasant and 'hey I built this!' and leave behind the 10% that is difficult anyway, and how you earn your pay... in fact they usually make that 10% significantly harder.)

Continuing the comparison to assembly, you still get people trying to spin Javascript as the Assembly language of the web, the code that all browsers speak, and it shows up in your debugger, but not what you want to be coding in. This kind of thinking is weak, because the additional layers, while slick and clever (epecially in the early baby tutorials) don't actually let you say stuff new. A concise essay about that in terms of toolkits is Uriel Katz' Why JavaScript is NOT the new Assembly  and a longer one against CoffeeScript and other pre-processor type languages is blog.izs.me's "JavaScript is Not Web Assembly".

Friday, November 11, 2011

not so angry birds

Today, our UX guy posted a link to Why Angry Birds is so successful and popular: a cognitive teardown of the user experience. This is the bulk of my resposne.

Cool article, though I disagree with what it assumes makes Angry Birds so popular.
The author is remiss in pointing out the obvious: some big chunk of Angry Bird’s addictiveness is because the base activity is a fun thing: it is fun and pleasant to launch a slingshot at a building of blocks.

At [Alleyoop, my College Readiness webcompany], we aren’t based on a core activity that offers such a low learning curve / high satisfaction + feedback . I think at the best points of [our Math practice and quiz subcomponent], kids can get that extra Zing! of satisfaction of a problem mastered, but in most other ways it’s a reach for us.

So with the article, I agree with some bits (the importance of pleasant and detailed visual design, even the inclusion of extra details like the chattering birds) and disagree with others (iPad icon spacing provoking a sense of tantalizing mystery? Puhleeze)

I thought margie's comment was more insightful to the charm of this particular game: (highlighting mine)
AB is a game for non-gamers. Gameplay is simple, the rewards are many and often, hence, continued play from all players. Any game that increases in difficulty and/or timing & speed too quickly I’ll drop out of […]. ~ AB is always the same: slingshot, birds, structures w/pigs.

I think the fact that players are frequently rewarded (it’s easy to pass a level, not so easy to 3 star a level) plays a huge part in why AB is so popular, especially with people who are not hardcore gamers.
Other commentators talk about “quick retrying ‘til I get it right” is a big aspect, maybe one we can learn from. Not punishing failure so much is a hallmark of modern gaming.

It’s funny too, the opening paragraphs:
Surprisingly, it is a rare client indeed who asks the opposing question: why is an interface so engaging that users cannot stop interacting with it?
The funny thing is, that’s not “engagement” so much as “low level addiction”. And frankly, popular games use some of the same pattern as drugs—an initial big rush (of success, in the case of games), a long haul of trying to recapture that high, and it being made harder to do so.

(It’s funny contrasting that with the addictiveness of say Farmville—there the addiction comes from a web of social obligations. The gameplay itself is decidedly NOT very fun in the way slingshots-at-buildings is, though it does carry a pleasant sense of “I Made This” construction. (I haven’t gotten into it either but I think Empires & Allies has those social and building aspects, along with an empowering “strong kid on the block” aspect in the fighting)

So I think [our company] would be well served if we could capture some of this addictiveness:
  • well balanced challenges with quick redo 
  • a carefully ramped increasing difficulty 
  • pleasant and juicy UI 
  • social obligations 
  • a sense of building 
The single biggest thing that Angry Birds and Farmville have that we don’t are a real feeling and visual model of steady progress. (With Angry Birds getting through a series of levels, with the chance to go back and do better, with Farmville a nicely expanded and built up farm.) [Our former point system is] now a currency. Badges were nice, but were always more of a novelty than a core “gotta catch ‘em all!” experience

BONUS:
Some more thoughts that were a bit too specific about Angry Birds as a game to be relevant to my company:
I think the article missed out one of the best UI bits for the "try again" factor: you get a little dotted line showing you what your last trajectory was, thus enabling a higher degree of fine tuning. This little dotted line is more significant than a lot of the things the article discusses.

Another thought I had: if I was designing Angry Birds, I might try to give it a split view: a zoomed-in view of the current bird (allowing more fine control of the trajectory at the launcher, and then a fun closeup view of the structure being destroyed, or possibly a pan back to the smug pigs if you totally miss) and then a view of the entire playfield, visible at all times. 

The thing is, I'm not sure if this system (more complex in its display, but simpler in its control scheme than panning and zooming Angry Birds) would be more or less satisfying than the current scheme. But when thinking about what deliberate choices Rovio made (vs, say, the delays once the bird has hit the building, which I think owes more to giving time to the physics engine to work things out than a deliberate design decision) alternative solutions to the challenges they faced should be discussed.

Wednesday, November 9, 2011

jsonp for cross-site fun

So, today's fun:
We run a few different servers for testing: www is our live site, cert is for final testing, test is for preliminary testing, and we hack DNS a bit so that dev loops back to each developer's machine.


We have a single WordPress install that we use for our blog, as well as to store the content for certain activities on the site. My most recent project was to add a simple tag system that would change a WP slug like 
[lookup value="user.profile.firstName"] 
into a rest call to /rest/user/profile and substitution with the fieldName parameter. (I also added conditional tags, something like 
[start_if value="user.grade" is="GRADE10"]Welcome to Tenth[end_if]
would display "Welcome to Tenth" only if the endpoint said that was their grade.


So when you just have the one WP install there's an obvious small problem when you want to test before pushing live, that while WP (which I keep accidentally calling "WordPerfect" not "WordPress", a habit that is catching on at work) can do its own preview, it's not part of the whole dev/test/cert/www cycle. We added a "src=http://dev.alleyoop.com" type parameter, telling the plugin where to pull its javascript guts and then rest calls from, but... d'ohh... the rest calls were failing, losing out to the draconian cross site scripting rules. 


The cool kids solution to this is JSONP, JSON-with-Padding. (The wikipedia page for it is a decent introduction.) The server needs to be configured to recongize a jsonp request, and then it forms a response of the form "<script>yourcallback(THE DATA)</script>"-- script tags aren't beholden to the usual xss rules. (Which is kind of a headscratcher, given that running code from another site seems to be a lot more dangerous than just grabbing data, but sometimes you have to take what you can get.)


So, in practice, I made a version of our wrapper for getting JSON that added a parameter dataType: "jsonp" to the jQuery.ajax call. We then ran smackdab into a kind of known Firefox issue (I'm not sure if us using a more up to date version of jQuery would have helped or not) where Firefox thinks that the JSON, what with its hashes and : and all, looks like it's trying to generate labels (what is this, BASIC?) and spits up "invalid label"... our fix for that was in the middle tier, a known solution is that wrapping the data in an additional set of parentheses fixes it, so that's what we did.


There's of course a bit of a security concern when you're allowing shenanigans like this-- especially if we were showing content from one user to another user. We'll look for some ways to tighten that up.

mobile flash in the pan

So the news is making the rounds, Adobe to stop doing mobile browser Flash.

For some Apple fans, this is a giant validation of Apple's view that Flash was the wrong technology for portable devices. (And as some have tweeted ActionScript might still be viable for making standalone apps.)

At work, our designer's response was "Aple wins!" and our lean startup guru marketing guy responded "The Internet wins!". That, along with Gruber's tweet thinking 2015 would mark the end of Desktop Flash players got me thinking...

What's next?

The most common opponent for Flash is usually described as "HTML5" which seems a little funny to me-- technically, HTML5 is about the semantics of markup, more of a topic for wonks than anyone else.

In practice, then It feels like there are two fronts for "not Flash", both powered by javascript. One is, and this is what I'm making my living with now, is what used to be called "DHTML"-- pages full of divs and graphics and one not, providing a faster and more interactive experience than the static pages of yore.

The other is stuff that makes heavy use of the "canvas" object. A lot of my gaming buddies are way into this as a technology. It's pretty cool, but there are two giant challenges for it to overcome to take the place of Flash: one is support for sound is still kind of iffy, you really have to dig if you want something that is very cross-browser and can provide "real time", synchronized sound effects. The other is support in IE (version 8 and earlier) tends to be lacking. (There are some libraries that use shims that do a good job of faking canvas support.)

I'm not sure what this means for me... Flash was on my "I should learn this" list, and now it's a little lower down.  (I took one 2 day intro class and it was frustrating because the class was geared at designers, and focused on the timeline, which STILL confuses me, as opposed to ActionScript, which felt very familiar when I helped a friend recode a few things.)

(UPDATE: Gruber also pointed to this CNET article that points out somethings Flash still does better than its alternatives...)

Tuesday, November 8, 2011

scope-a-dope

This is one of those posts that I'm a little nervous about writing, because I worry I might look a bit bad, since it represents a small bit of "trial and error" coding along with a slightly iffy theoretical understanding of the problem. Still, in the interest of being useful to my future self and maybe showing other people they're in the same boat, I'll put the process here.

I was trying to do a bit of caching of some data asynchronously.I had "neededEndpoints" that was a hash of the endpoints I needed to hit and store the data for in another hash, call it cache

So here was my first attempt: (it didn't look so blatantly wrong when I coded it, I've stripped out stuff in the name of simplicity)

for(var endpoint in neededEndpoints){
 jsonGet("/rest/"+endpoint, function(res){
                   cache[endpoint] = res;
             });
}

The trouble with this code is that javascript is not block scoped like some other C-like languages, and so "endpoint" is effectively passed by reference, not by value, and the last value of "endpoint" was used for all the cache storing.

I remembered in previous work we'd done here, we had a CreateDelegate function:
function CreateDelegate(scope, fn) {
    return function () {
    if(fn != undefined){
    fn.apply(scope, arguments);
    }
    };
}
Usually we'd call it with "this" as the argument for scope, but I wasn't getting the results I expected. Googling I found this page that gave me the nudge I needed to come up with this:
for(var endpoint in this.neededEndpoints){
 jsonGet("/rest/"+endpoint, 
               CreateDelegate({"ep":endpoint}, function(res){
cache[this.ep] = res;
   })
 );
}
So what's going on? The mental model I've come up with says CreateDelegate is in effect making a snapshot of the current state of things-- that's what a delegate is, in effect. It's actually the act of instantiation of CreateDelegate that makes the snapshot, and then the code inside it can have exactly the context we give it.


thoughts on keeping the global namespace clean

So one well known issue with javascript is that it's a bit too easy to pollute the global namespace.

Personally I find this is a big issue more in theory than in practice, choose reasonably distinct function and variable names, and you hardly ever have a problem.

Half the problem is that if you just start using a variable without a "var" declaration, it gets slapped into the global namespace. Douglas Crockford, among others, considers it a bit of misstep in the design of the language.

(The other half of the problem is the same "bootstrapping" problem any language faces: how do you tell the system where code execution starts, and where is the tree of object and functions rooted ? C and Java have their main(); in Javascript, you can start putting function declerations and even calls anywhere, in practice there's a lot of $(document).ready(function(){}); )

So, you can go a little crazy with loaders and tools to control your namespace and keep your private variables and functions private etc, and also with CreateDelegate() functions to pass thing to page elements and whatnot. This is overkill for most projects where you're more interested in the functioning of the site than making a reusable toolkit. (YMMV). A good compromise is "make one global variable per functional grouping". For example, today I was working on a "madlibs" controller (for eventual integration as a WordPress plugin) Part of the code for that was:
var ao_madlibs = new function(){
  this.neededEndpoints = {};
  this.doMadLibs = function(){
//CODE GOES HERE
    } //end doMadLibs
 }//end ao_madlibs


In practice I find this a good balance of control and ease of reading. One caveat, in the doMadLibs code I used jQuery's .each() function, and in the anonymous function in there, "this" had a different meaning, so I had to use the global reference ao_madlibs.


I was looking at a bit of coworkers' code... he's more of an architect, and cribbed this from FB's api code:

if (!window.AO) {
    window.AO = {
    processElements : function(){
                  //do something
        },

        someVariable: {}
   };
}
This code is using more of the associative array syntax, plus doing that check to make sure it's only called once. I find it's a little more "foreign" looking to me, but makes a good amount of sense if you're used to JS's variable syntax. Pick your poison I guess! Sometimes I do miss Java's class structure syntax...


The nice thing about using a global variable, to, is that you can really easily and concisely refer to your "functional grouping" in page elements and in other parts of your system, again without worrying about ever-changing meaning of "this" and using tons of oddball CreateDelegate functions... I find KISS (Keep it Simple Stupid) to be an important principle in making code I can read in the future, and in communicating my intent to other people looking at my code.