warpedvisions.org

ESSAYS, HOW-TO ARTICLES, AND GENERAL MAKERY BY BRUCE ALDERSON.

As designers, software developers, and business geeks we thrive on a few things. We seek inspiration. We obsess over details. We work long hours. And we need focus.

Computers and software have evolved to the point where nearly anything is possible. It's an amazing threshold, as we are rarely limited by the hardware, OS, and languages. We're mostly limited by our own ability to produce. We are the weakest link in our productivity.

Enter the era of focus applications. We've seen focus tools over the years, but the market has matured and there are dozens of tools available to help our focus.

Hocusfoc.us

One such tool is Hocus Focus. It is a simple tool. It minimizes applications that you're not currently using after a fixed timeout. That's it.

It's an interesting way to work. I usually have several windows open at once as work, ideas, and life are interruptive. A tool like Hocus Focus lets the interruptions happen, cleaning up after the chaos.

Hocus Focus may not be an every day tool, so it lets you disable it when you're working on something that requires a bit of mess. It also lets you customize the timeouts in a few ways, in case you have applications that need to be more persistent.

Does it work? I think so. Application disappearing takes a bit of getting used to (a fade might be better), but once you stop noticing applications dropping like flies you're left with a desktop that is more focused.

#Weblog

As a software designer, I love to design software. As software developer, I love building software. When I dream of better things, I funnel my ideas into new projects. When I don't have time for all of my side projects, the projects pile up in a corner and gather dust. And when a side project is an unfinished publishing platform it gets in the way of writing.

I'm intensly interested in writing and publishing on the web. There are just so many possibilities for saying interesting things and making the presentation of those things more useful. I've dedicated a chunk of my consulting time to making beautiful interactive sites for non-profits, and I use a slice of my spare time for maintaining a number of my own sites (and those of friends and family). I believe that what we're seeing on the web today is a shadow of what we will publish in the future, and it excites me.

My love for writing and publishing led me to building my own minimalist tool. Chronicle.md is a Markdown app written in PHP. It works as well as a first version needs to work, but it isn't productive enough yet to invite me to write daily or weekly. It requires twiddling and poking to get posts out, and it doesn't support any of the common publishing APIs. And as it's not at the top of the pile of awe inspiring ideas, it's not going to get those features any time soon.

And when I weigh the importance of building a better tool with my need to write, writing wins.

So I'm back to WordPress. It's a reasonable tool, with a vast, stable API, with hundreds of tools and plugins to make it sing. And as I've built hundreds of custom themes for it, I can spend some of my fun development time making WordPress better.

The straw that broke the developer's ego

The tipping point this time around was the simple lack of writing apps that supported my custom tool (hint: this number was 0). As I have been itching to try Desk.pm (a writing tool that supports CMS's like WordPress), and as I have been publishing sporatically, it was time for a change.

Now I can dream of ways to make my writing flow better, instead of building everything at once. This fits the character of side projects better, as I can take bite sized problems, related to my writing needs (or my client's needs), and solve them really well. It's all about focus.

If I do decide to build a CMS in the future, I will make it my main gig, instead of trying to fit it inbetween the other stuff. Letting side projects interfere with your flow is a sure sign that the balance is wrong.

In the interim, when I get the itch to invent a new CMS, I will aim my powers at trinkets, plugins, and themes for WordPress (and other CMS's).

#Weblog

I wrote my first computer program when I was 8. It was a simple adventure game written in BASIC, a mess of GOTO and PRINT statements. I saved it to tape a few times, proud enough of my first creation that I didn't want to lose it. And despite what I didn't understand my mind exploded with ideas.

I continued to write games and curios into my early teens. I wrote text adventures and arcade ripoffs. I hacked at biometric data collection using a busted set of paddles and mixed mode graphics. I designed and built a large (but clunky) side scrolling adventure game using only a set of customized fonts. I plagiarized code from magazines and hacked at my machine until the wee hours of the night.

I learned almost nothing about writing production code in my early years. And while discovered that I loved to imagine and build things in code, I barely brushed against the principles that would later be required to make real learning possible. My skills didn't improve much either as my time was largely unfocused.

I was a hobbyist. I discovered the joy and love of software, but entirely missed the nuts and bolts of it. I didn't learn anything about the science, the skills, the mechanics, or the business behind software, which limited how much I could learn and improve. It's a limit that prevents most of us from eclipsing hobbyist, even those who end up making a profession of it. Failing to escape hobbyist damns you to a shallow relationship with understanding.

“You want to know how to paint a perfect painting? It's easy. Make > yourself perfect and then just paint naturally.” > #

But it's more than just knowledge. After you discovery where to start learning the right things, you must then endeavour to follow it with practice. Failing to practice leads to a lack of reinforcement and eventual atrophy.

A sideways journey

I shied away from computers as high school progressed. I was bored with my slow progress and was naturally gravitating away from solitary activities. Instead, I spent time with friends and worked in various menial jobs. I enjoyed working too, especially in restaurants where I was making food with my hands (even fast food).

I made my way to college, and wandered through it mostly without direction. I passively avoided computer science, though I found myself programming in various capacities anyways. I wrote software for restaurants, built data analysis code for agriculture and biology courses, and coded simple tools for print operations. I was still sure that I wasn't a programmer, so I continued working in restaurants and studying anything but computer science.

I also considered myself an artist at the time, even though I spent very little time being artistic. I would binge on art from time to time, especially enjoying block printing and photography. I also enjoyed sketching, though I never reached the escape velocity required to do much more than doodle icons and simple caricatures.

It was around this time that I realized that I wasn't really very good at anything I did. I mistakenly suspected that I wasn't trying hard enough, so I doubled down on my studies and changed my major to computer science, as it seemed somewhat inevitable.

“The truth knocks on the door and you say, “Go away, I'm looking for > the truth,” and so it goes away. Puzzling.” > #

Unfortunately, trying harder was a vague proposition, and I found myself bored when my lack of skill eclipsed my need to produce useful software. I did well in my studies and project work, but I didn't really learn how to write software despite writing quite a lot of it.

A first glimpse

I developed a schizophrenic relationship with making things though college. My mind would race at the prospect of building something, excited to get started. I would enjoy the tedium of construction and I would revel in finishing. But at some point in every project I would realize how far from great it was.

I tried to ignore the reality: I didn't enjoy thinking about how much I didn't know and how limited my abilities were, even though the thinking about those things would have pointed me toward improvement sooner. I continued along a superficial path of creation for many years. It was a dichotomy that would follow me for some time, the excitement and passion for making things, and the inevidable disappointment of knowing they weren't great.

I continued meandering through college, bored with my classes and part time work. I left my program early for an opportunity to work in the real world, hoping that it would nudge me out my rut. And it did.

When you want to hurry something, that means you no longer care about > it and want to get on to other things. > #

My first few years as a full time professional were liberating. I was working as part of a team where my lack of skill and knowledge were no longer limiting. We were given simple, defined problems to solve, mostly tied to specific customer support requests. The team was knowledgable, at least in terms of how to solve specific problems, so I was able to start and finish projects quickly and with some quality.

Smaller, more defined work was the first step to successful practice. Our time was limited by customer deadlines, which forced us to keep our approaches and designs simple as well. Combine small and simple with compiled languages, and we kept the code clean too. This principle drilled a few things into my head that were important, though I wouldn't fully grasp them until later.

This first real software job was important in another way: it showed me how little I knew. Both through the practice of churning out a release every few weeks and the fellowship of our early staff I came to realize that I was still just a fledgling in the craft. And as luck would have it, the employer embraced continued learning and they graced us with a very ample book budget. I spent every penny I could of that budget, and read every book cover to cover numerous times. I felt like I was finally learning.

Of course I had already learned more than I realized, but by this time I had some experience and perspective. My experience helped me focus the time I spent learning, and it helped me filter the learning materials too. Both focused time and quality inputs are important for learning, as is having enough perspective to see the value in what's being learned.

Clearer motivation

After my first few years as a professional I became aware of how making things affected me. I learned that when I made something the experience was deeply satisfying. And as my results improved, the experience was better. In short, making things felt good. Getting better at making things felt incredible.

“Logic presumes a separation of subject from object; therefore logic > is not final wisdom.This is Zen. This is my motorcycle maintenance. “

There is a problem, however, with associating satisfaction with making, especially when it's your profession. Sometimes you are forced into unsuccessful projects, either through simple missteps or through external pressures. When we are attached to the our successes, our failures become part of us too, and we suffer emotionally and physically.

Over the years I've had to fight the attachment to the things I make. On one hand there is great satisfaction in the process. On the other hand the failures eat away at who you are. Conflating satisfaction with value is an expensive mistake that I'm only now learning how to avoid.

I am neither my success nor my failure, nor am I the journey. In the end I am who I choose to be, in how I allow the experience affect me, and how I perceive the journey itself. I'm not suggesting rose-coloured glasses, rather that you accept the reality (whatever it be) and choose who you become (or who you don't become), without prejudice. This plays for both success and failure, and for the things in between, as lot of what we do in computing is on the long road between inception and shipping.

The sum of the parts, mostly

I look back on those early successes when I get lost in software development. I also look back on the time when I started to understand learning as a reminder of what I can do when the inputs and circumstances are just right. These experiences help me find my way back to reality, inspiring me, and reminding me what can be done.

Looking back on some of my earliest, successful projects also gives me a sense of perspective, one I could not have found at the time. Those early projects were not as bad as I thought they were. They were a balance of pragmatic, functional, and creative (at least the ones I remember). I often find myself wishing I could find that balance again, a balance that I was forced into by my lack of knowledge and experience, a balance that is now more difficult to find.

Some of our art is in learning how to learn, learning how to practice and hone our craft, and in exercising our experience and knowledge. The craft is also in finding that child-like simplicity, where the balance hinges on the limitations more than the infinite possibilities, and where that youthful passion is clearly seen in the things we make.

#Weblog

I review a lot of code these days. It's an incredible way to nudge a team of bright people toward greatness. It allows me to look at problems from the outside with a perspective of experience and distance from the low level design. The perspective is important too, and I see things that I often miss in my own code. You see, we're easily blinded when we're too close to the problems we're trying to solve.

A change in perspective is worth 80 IQ points. —– Alan Kay

Think of it like this: walk up to the front of a large building. You won't be able to see around it anymore: the roads leading away from it are obscured, and the metropolis surrounding it is dwarfed by its stature. Your perspective limits you.

Rule 0: no one has immunity

I require review for most code that comes from my teams, including my own. Github pull requests are a great tool for this, as you package up a change, relate it to a bunch of tracked issues, and open it up for peer review. It allows you and your team to comment, iterate, and accept or deny each patch. There are lots of other ways to do this, of course, but the mix of branching and discourse is brilliant.

Rule 1: reviewed code is always better code

You don't have to review all of the code produced by your teams, but it is incredible value for the effort. It's far easy to bump design and learning along in small steps, and far cheaper too. There are fewer surprises, fewer rewrites, and a much easier learning curve for everyone.

I can review code for a few teams of developers, given a mix of skills, in a few hours a day. That includes time to talk over issues with individuals and group whiteboard sessions. The code review leads to design review, and a solid understanding of where your teams stands on a daily basis. Getting the team productive gets you to shipping.

Rule 2: develop simple ways to sample code

Understanding every line of code is difficult, especially given the chaos that creeps into the daily life of a team lead. Even after taming the chaos you still need to find ways to focus on code in ways that finds the important holes. How do I do this? Simple heuristics, or in other words: rules for finding crap.

For example, when reviewing anything in Python, Ruby, Perl, or PHP, I look for programming conventions from other languages. Parsing strings using strpos? Is there a better way in the language? Is there a faster way? Is there a cleaner way? I call this: alien syndrome. It's easy to spot, and even though it's sometimes the best solution, it's more often a sign of a developer who has failed to really understand the language. A sign that they're limiting their thinking to what they know and not in the potential of the tool at hand.

Rule 3: write down your rules and philosophies

Write your rules and style guidelines down and share them with the team. Make them into manifestos or a top-$n list. Have fun with it.

Here's my 8-bit list for reviewing code:

  1. Alien syndrome – the code uses a convention or mechanism from a different style of language. C-isms in Python? That's weird!
  2. Exception litter – a function spreads its error cases throughout larger algorithms. Is the data unreliable? Failing early seems more humane than dragging it out.
  3. In-and-out buggers – the code mixes generation with logic. Can the logic be split into something more easily tested? Can the generation be split into some sort of adapter or template?
  4. Elbow-itis – the design or code has several elbows. Does the complexity of the code or design fit the complexity of the feature? Not!
  5. Inconceivable – language or library functions used in odd ways, or where much better mechanisms are available with a bit of searching. Do the functions do what the developer thinks they mean to do? Various uses of regex are especially subject, as they represent incredibly dense logic.
  6. Are we there yet? – algorithms or classes that drone on well past their welcome. What makes the code so lengthy? The rhythm of the code is much like prose: it should feel good, not boring.
  7. How DRY I am – repeated code is stupid. I may be lazy, but testing something more than once is crazy talk. It's also expensive and prone to errors on several levels. Bad mojo!
  8. Preflight sanity – code fails the basic mustard: neat, tidy, edible, digestible, and food-safe. Loose lips sink ships. Sloppy code is crap. Or, if code can't meet basic minimum limits, then it's likely flawed in other ways.

I add heuristics regularly, based on simple misconceptions, new techniques, or especially creative developers (often including myself). I focus on different types of problems with different developers, and with different types of designs.

Rule 4: review should use what people do best

Let the computers worry about syntax checking, enforcing persnickety grammar rules, and testing for large and complex things. Code review does not replace the compiler, the lint tools, the unit tests, the system tests, or the load tests. How could it?

I focus my time on things that I can use to teach better techniques, on patterns I can use to prevent entire classes of problems in the future. In the rare case where there are grievous basic issues, I call everyone to the bat cave.

Rule 5: to the bat cave!

Some problems deserve more than one-on-one time or group training. You know the type of problem I'm talking about: that API that's warty and gross, or those SQL queries that are covered in slop. Picking these things apart piece by piece would be painful and cruel. Didn't someone tell you not to pick at the scabby things? No?!

These loathsome problems require a graft and not just a simple nudge. Solve the problem properly, cleanly, and with some tact. No sense in making it painful or tedious. Write a standard or a guideline, and plan some real time to scour the grit out of the gunk. Fix it up right, and take the fix out of band to the mess it solves. No sense in dragging developers through the mud. Pick them up, set them straight, and show them how to solve the problem properly.

Rule 6: there is no rule 6

There are always problems that don't fit your experience. Roll with it and remember your team is awesome. Support them, look for the long game, and base your recommendations on solid first principles and fact. Keep it clean. Keep it fun. And remember: code review is a form of programming itself. You're encoding your team's success using a simple series of feedback loops.

#SoftwareEngineering #TheArtOf

July 25, 2013

You can pass data between the client and server in a number of ways. I like to mirror data structures between my server and client, so that I have the same basic data model available in both realms. There are a few ways to do this, including:

  • Calling an API that returns JSON (or JSONP)
  • Calling an API that returns some UI, which can include some JSON
  • Getting an entire page that includes your data model in JSON

Sending a client data is trivial in most dynamic languages, and PHP is no different. You return a response body with the result of a json_encode and your data model. The technique works just as well in APIs as it does in standard HTML templates:

<h1>Some HTML</h1>
<script>
    var my_object = <?= json_encode($my_object); ?>;
</script>

The result is a mirror of your server side structure on the client. You should encode your object somewhere else (like in your framework), as you should take care to ensure that the result is valid, but the simplified example shows the basic process.

You can replace these data objects from the server in subsequent requests too, ether in JSON calls or when requesting subsequent chunks of HTML (by including the same script tag). The technique lets you keep your client and server model in sync, to whatever degree your application requires. It also helps force your thinking to data structures, which gives you a chance to properly model what your application needs.

#PHP

PHP is a great language. It follows a long lineage of C-based syntaxes, mirroring much of the C standard library. It performs well, is trivial to deploy, and has been stable for many years. And, it's almost universally hated.

While many people look down on PHP, it's worth considering where it shines compared to other languages. I find that in many uses, PHP provides a great set of features and elegance. Not only is it competent, but there are places where it is truly a great little tool.

But first, what's up with the hate?

PHP is old

PHP has changed over the years. The result is a language specification that has (at times) been incompatible with previous versions. It also has produced a warty standard library, with a large variety of naming and programming conventions. I agree that this should be improved.

On the other hand, the current language is expressive, and the runtime libraries are vast and rich. Any good code editor will provide auto-complete (and API references). I've found PHP no more difficult to navigate than C, C++, Java, or Ruby, though I'll agree that Ruby is a lot tidier.

Too much dynamite

Another common complaint has to do with PHP's automatic dynamic type casting system and how it can be confusing. This stems from versions of PHP prior to 5, though there are still a few edges where the language can be used incorrectly to produce incorrect results. Namely, when comparing dynamic types, take care to read the documentation and use the appropriate casts and operators.

Library quality, thread safety, and so on

Other complaints include varying library quality (this is a problem in most of the languages I've used), and thread safety (also a common problem). These problems have never blocked anything I've used PHP for over the years, as I use it for problems it fits well.

There are also other language quirks that frustrate people, things like ternary behaviour, historic security issues, error handling, and so on. My assertion is that, yes, PHP is quirky, but no more so than Javascript or Perl (or many other languages). I find that PHP produces very readable, predictable code for a few specific problems. This makes it a great tool for those problems, despite the hate.

So what's to love?

If you can get over the warts, there are many features in PHP that come together to make a solid set of template and API building tools. PHP is designed as a thin veneer over HTTP requests, with enough finesse to build simple, clean interfaces.

My favourite PHP features:

  1. Dynamic class loading, allowing you to register your own loader for classes that are requested by code and not found in the current namespace. It makes it possible to handle installation errors nicely, dynamically create modules at runtime, or provide custom loading of nearly any sort.
  2. Dynamic class accessors, a feature that allows you to provide class accessors with a single function, making it trivial to provide clean and consistent error messages with a minimum amount of code.
  3. Dynamic call dispatching allows you to route class member calls through a single function. This makes it simple to provide a learning interface, one that can probe a remote API and dispatch based on the results. The syntax to the caller is clean, and it implements with only a single function point.
  4. First order templates. PHP is a template language at its base. It allows you to represent output in the output's format, hooking to the language with an obvious syntax. With its ability to set the variable namespace, it makes for a rich, performant template system.
  5. HTTP/CGI at its base. PHP, when started by a web server, is primed and ready to go. No additional libraries are needed, and very little work is required to parse a request and produce a response. This makes it possible to service web service requests with minimal overhead (though oddly most PHP frameworks do not do so).

There is more to love too. PHP has a solid set of mechanisms for defining classes and namespaces. It provides interpolated strings and oldschool HEREDOCs. Many of its core features and libraries are implemented in C (and perform well). Given a reasonable amount of discipline it produces predictable, useful code ... about the same amount of discipline required to work effectively in Javascript or Perl.

PHP isn't for every problem. For example, I find that it's a poor fit for shell tools (Bash, Perl, Ruby and Python are much nicer here). It also doesn't scale to huge server side things on its own (Java? Ruby?). And it doesn't have the rich ecosystem of things like Ruby and Rails. But, PHP is a solid tool in my kit, especially suited for lean web things.

#PHP #Software Engineering

A developer asked me a seemingly obvious question today:

I have an API GET request that requires a JSON body. Is that okay?

It's a good question too. It turns out the answer isn't as simple as it should be. On principle the answer is, “No, it's not cool”. A GET is an idempotent request for a resource. You don't request a resource with a resource (what would that mean?), you request it with a resource identifier. The HTTP spec, however, is unclear on the subject and does not explicitly disallow it (it probably should).

This developer was using the request body as a convenient way to send a complex set of parameters, as JSON is much more useful to work with than URI encoded components. His approach was both sane and pragmatic. But, it was also incorrect.

A few minutes of reading confirmed my take on it: GET requests with payloads are bad mojo. But why is that, though?

Four reasons why you should avoid payloads GET requests

  1. It's unexpected. You are not guaranteed that all HTTP implementations will treat it in the same way.
  2. The spec says so, sort of. Servers could/should ignore request bodies, as they have no semantic meaning to the request.
  3. It doesn't play nicely with caching. Many caching layers use the URI as the cache hash. Unless the URI is changing between requests, the payload will not change the result of the request.
  4. It's disingenuous. A GET request uses a URI to name the resource. The request body is irrelevant to that request.

Sometimes the simplest questions are not answered by the spec.

And how does the story end?

The developer recast the GET as a POST. The semantic of the request was to retrieve a customized resource based on specific parameters, essentially creating a new resource on the fly based on the given parameters. As the filters were non-trivial, they could not be cast as HTTP headers or components of the URI. This was a pragmatic fix too (one line in his tool chain).

#HTTP

I've been busy working on visual design bits for work projects this summer. My method is simple:

  1. Sketches and storyboards
  2. Static mockups (HTML/CSS, some Javascript)
  3. Live mockups (to test integration and interactions)

Uncovering what a feature means is fundamental to the method. It exposes the nouns and verbs of the problem, and hints at the useful metaphors. The freeform nature of sketching and developing storyboards based on this language helps me focus on figuring out what the things mean, as well as finding their shape and rhythm. I end up working on several different approaches before it's obvious which ones are workable for the client and product.

Moving to static and live mockups transforms these ideas into reality. I aim mockups to be as close to production quality as possible, as anything less distracts from thinking and the discussing the designs. These distractions are the worst sort too, derailing any shared thinking on how an interface should be.

The method is important. It's worth practicing, and I do on a weekly basis (I'm always designing something).

Recent examples

I haven't posted much ongoing design here, mostly as I haven't been that proud of it (or haven't been the primary designer on the projects). As my hone my craft, and as I work on more interesting projects, I will talk more about my work. This is a good thing.

Inline bar graphs.

This is part of an updated reporting project. I found that the bold graph elements and combined (and pivoted cell data) improved readability of the table. Realizing that different types of columns had vastly different visual needs (as they were different things) improved the clarity of the data overall.

Simplified application chrome.

The simplified application chrome is part of an ongoing improvement project. We're reducing the size of the chrome (or bling), so that the guts of the application are much more prominent. The previous design had about 35% of the page dedicated to this chrome, which is now about 10% of the overall vertical space. We've hit the basic brand colours and shapes, improving the clarity of the product name itself and removing unneeded navigation.

Smaller, graphicless login.

I've also simplified the sign in form. Nothing revolutionary, but we've reduced the size and amount of noise significantly.

Learning is doing

This summer's design projects reinforced a number of principles for me:

  • Process is bullshit. Method and practice, however, are crucial to execution and skill.
  • Freeform thinking before structure. Sketching beats regimented tools for creativity.
  • Make it real as soon as you know what it is. CSS/HTML designs look better than sliced or faked graphics, and you can get to testing usefulness sooner.
  • The little tools and techniques matter. Icon fonts are awesome sauce. LINT, minification, and LESS improve quality by reducing duplication and effort.
  • Small design steps are easier to finish well. Increment methodically. Build testing into your core habits, into your product.
  • Simpler writing tools result in better writing, and writing really matters. Simpler tools are better. Simpler editors, markup, and hosting.

Hammering at the methodology and practicing each of the individual skills shows results quickly. I'm able to prototype a new set of features in a few days now, assuming functioning creative mojo. Iterating design with shorter design stints makes for more polish. Wax on, wax off, and all that.

#Design

Friction works against you. It exceeds your ability to progress. It deflates you, stripping your motivation. It's the hill you see before starting a difficult project. It's the gravity that pulls you away when interest wanes.

I'm starting a small project for a client today. It's a simple set of improvements to something I built for them last year, using a toolkit I wouldn't normally use (but one that fit their uses well enough). I had forgotten a lot about the toolkit when quoting on the work, and by the time I remember it's clear that there are challenges ahead of me.

When it comes time to start the work I find that I'm stuck. Unmotivated. Paralyzed. I'm staring up the barrel of an uphill battle.

To get unstuck I need to start moving. I need to realize that the problems are soluble and mostly in my head. And the best way to get started is to do something, anything at all.

So I work my way around the edges of the harder problems. I simplify development by working on a scratch copy of the project, isolating and reducing the size of each individual piece. I work outside of the warty toolkit and test my work carefully before integrating it. I carefully break my work down into lists of small achievements so that I can make measured progress hourly. Once I get a piece working I test it, and put it up on the shelf. By the time I finish the small bits I'm moving, and I can attack the mountain without distraction and with gusto.

And the mountain? It was a projection of my imagination. I thought the work was going to be difficult. I believed it. I didn't feel like re-learning the old, warty tools. I remembered the flaws more than the good qualities. Or maybe it was one of hundreds of other human flaws manifested as part of my fictitious friction. The key was to realize that friction was just a glitch in my perception, that if I shed my perception I could do it, that once I started the work it would be easy. And it was.

In other words: just fucking do it already. It won't be as hard as you think. And if it is, you'll be done before you realize it.

#Weblog

One of my favourite JavaScript features is its literal object notation. It allows you to declare data structures in JSON, which is a very succinct, C-like syntax. You can use this notation to declare SETs, and the a in b syntax to verify a variable is in a set:

/* Declare your set as a JSON constant */
var valid_widgets = { 
    'widget-viewer': 1,
    'special-viewer': 1,
    'widget-editor': 1 
};

/* Fail if something isn't in the set */
if ( ! (options.widget in valid_widgets) )
    return false;

/* Profit! */

As the in keyword operates on the index of the referred object, we set the value of the constants to 1 (true). A bit of a hack, but it results in a very clean way of checking if something is part of a set of valid values.

#Weblog

Enter your email to subscribe to updates.