Skip to main content
Ben Nadel at the jQuery Conference 2010 (Boston, MA) with: Elijah Manor
Ben Nadel at the jQuery Conference 2010 (Boston, MA) with: Elijah Manor

Javascript Patterns By Stoyan Stefanov

By
Published in , Comments (23)

Over the weekend, I finished reading Javascript Patterns by Stoyan Stefanov. This book aggregates a large number of problem solving techniques that have been developed both by Stoyan Stefanov and the web development community as a whole. Unlike older "design pattern" books, Javascript Patterns explores solutions in the context of Javascript and the special nuances that it entails. While the book is advanced in nature, I would recommend it to everyone as it provides a great overview of what the language can do while including critical points of insight into how the language actually works.


 
 
 

 
Javascript Patterns By Stoyan Stefanov As Reviewed By Ben Nadel.  
 
 
 

I've been wanting to read this book for a few weeks, but the final impetus to buy the book came from Rebecca Murphey. In a conversation I was having with her about pub/sub, she suggested that I read this book to help open my mind. Ironically, neither of the two decoupled-communication examples in the book (Mediator, Observer [aka Pub/Sub]) used a global event mechanism like the kind used in Peter Higgins's jQuery pub/sub plugin (the pub/sub approach Rebecca and I were discussing). These patterns were, nonetheless, very interesting and eye-opening. Thick-client application architecture, as a whole, is something that I am currently struggling to wrap my head around and seeing all of these various approaches is providing me with some delicious food for thought.

On a completely esoteric note, I think this book may have convinced me to finally try using Regular Expression literals. One topic that Stefanov covers is the difference between (little-O) object constructors and (little-O) object literals. For as long as I have been writing regular expressions in Javascript, I have preferred using the "new RegExp()" object constructor over the "/pattern/flags" object literal. I can't say why, but there was something in the way he explained the two (and the meaningful differences that exist) that actually made me want to see how the other side lives.

Over all, this book provides a ton of great technical information that I'm still digesting; but, one thing that I rather enjoyed about this book was that it covered not just technical solutions but also coding style. In particular, I thought Stefanov explained vertical white space in the most clear, most succinct way that I have ever seen:

An often-overlooked aspect of code readability is the use of vertical white space. You can use blank lines to separate units of code, just as paragraphs are used in literature to separate ideas.

If you've followed my blog for more than a few days, you'll know that I love me some white space. True, I might use more than most people; but, I think what Stefanov is saying here makes complete sense. Staring at a file where every single line is a new piece of code is as difficult as staring at a page of text that has no line breaks.

Just think about it this way - how many times have you opened up an email that contains nothing but a single paragraph, 30 lines long, and thought yourself - There is NO way that I'm reading that now. Why? Because it feels overwhelming to even begin reading. And, as Stefanov notes in the book, you spend way more time reading code than you do writing it.

On another meta-programming note, I thought Stefanov made a brilliant observation about code and its evolution over time. I have long thought of version-one software as a "proof of concept." It was nice to hear this mentality echoed back as a "pattern" of excellent software development:

Talking about first drafts, there's also the idea of "plan to throw one away." It may look a little extreme at first, but it makes a lot of sense, especially when you have a mission-critical project at hand (and human lives depend on it). The idea is that the first solution you come up with should be thrown away and then you start from scratch. The first solution may be a working solution, but it's nothing more than a draft, one example way to solve a problem. The second solution will always be better, because you now have a much deeper understanding of the problem. In the second solution, you're also not allowed to copy-paste from the first one, which helps prevent you from taking shortcuts or settling for the non-perfect solution.

I know that that neither of the last two points have been about problem solving per say. But, I think that's part of what makes this book so good - it approaches Javascript development holistically, examining all aspects of the thought process from thinking about how to solve the problems to thinking about to write the code that solves the problems. The point being, the more you think about the code - the more cognizant you are of your code - the better your code will end up being.

Javascript Patterns seems to hit the sweet spot of complexity and clarity. It covers high level concepts using small, manageable examples in a way that is not too difficult to understand. As with all design patterns, though, they never truly get driven home until you try them out for yourself; I hope to dive much deeper into all of this stuff in the near future. And who knows, I might even start to understand the rules of pub/sub one of these days!

Reader Comments

5 Comments

Glad to hear you got a chance to check out the book -- it sounds like you enjoyed it as much as I did :) Re pubsub ... again, it's important to remember it is a *tool* more than a pattern. In my mind, it could be used to implement some of the patterns discussed in the book, but it doesn't surprise me that Stoyan didn't discuss it specifically.

Now if only I can get all of my clients to read the book, I'd be all set :)

15,902 Comments

@Rebecca,

It was definitely a good book; and seeing all these different approaches *is* making me think more deeply about software architecture. I liked the mediator and observer patterns because they were more akin to the event-driven programming that I see in the DOM.

However, I recently read a great article on Script Junkie that uses a sandbox approach with more "general" eventing:

http://msdn.microsoft.com/en-us/scriptjunkie/gg314983.aspx

When I read that, it *also* made sense :D

I think at this point, I really need to roll up my sleeves and try some of this stuff out in the field. Talking about it is one thing - doing it is another. I just need to come up with a good idea to play with... perhaps a new hackathon this weeked!

@Michael,

That looks good. I've read Pro Javascript Techniques, but not "Design Patterns"... at least I don't think I have :) I'll be sure to check it out.

15,902 Comments

@Rebecca,

Also, I hope I don't come across as being critical about our conversations. If I didn't have people like you to hassle for advices, I don't even want to think of where'd I'd be :)

5 Comments

Hey Ben,

I totally agree in recommending this book. Its a fantastic way for developers to see how common patterns we utilize everyday *should* be implemented from a JS perspective. This and high performance JS by oreilly are pretty much must read books for anyone considering building anything serious in Javascript.

@Michael, Having read both these books I much prefer this one over the pro js design patterns. I felt that while that book offered some interesting solutions to patterns, it didnt emphasize enough on the right way to do those things in a dynamic non-class based OO language. Going to great lengths to add their own classes to deal with things like interfaces and such just prove they are shoe-horning solutions from other languages into JS and that is not the right way to go about these things.

I think one of the best things to be gained from this book is its coverage of anti-patterns and why common usages are such bad practice.

At just over a 200 pages, and being a smaller format book, this could easily be tackled in a week of evening reading and I really suggest everyone should pick it up.

81 Comments

#Whitespace, #Readability:

One of the whitespace avoidance patterns I never use is putting { at end of line and } at beginning of line followed by something else. The reason is that { and } have syntactical significance, so they should be visibly indented with the block they define. Furthermore, the end-of-line/beginning-of-line practice as much as forces you to use { and } on every if, for, while, etc. It's a kind of OCD.

I haven't yet figured out how to indent code in Ben's textareas, but I'll try non-breaking spaces this time. This is how I indent code:

if (condition)
  {
  line 1;
  line 2;
  }
else
  line 3;

There's no way you can miss seeing the braces when you intent that way. And you don't have to use braces every time (as in the else condition).

What got me into this habit was having to work with monitors that weren't wide enough. I don't have to scroll horizontally to see how the line ends. Everything syntactically significant is right there with the code it affects.

Call me an Algol coder (that's how Algol's BEGIN and END were indented), but practical experience has shown that, if YOU were the last person to work on a passage of code, YOU will be the first person management calls upon to fix it. So you might as well make the code readable for YOURSELF and screw all the current fashions that show you took a C course in college.

Now get off my lawn!

15,902 Comments

@Simeon,

I have also heard excellent things about High Performance Javascript. Perhaps that will be the next one on my queue.

@WebManWalking,

Sorry about the indenting :) Now, with the CODE tags, the formatter will actually respect spaces... sort of. It tries to replace 4 spaces with a tab and then 2 spaces with a tab. Basically, it does something like this (off the top of my head):

^[ ]{2,4} ==> tab

It will also use tabs if you copy/paste from somewhere else as long as you use the CODE tags around it.

That said, I happen to be a fan of the braces on the same line as the statement. However, I should also caveat that with the fact that I *always* use them. As such, the IF or ELSE statement is the syntactically special statement as it is always grouped with a brace (ie. the brace isn't special on its own).

No matter where you put them (same line or next line), I would recommend always using them. I think the "optionality" of them is more dangerous than anything else, especially if someone else might be working with your code.

But, again, some of this stuff is just straight up personal preference.

54 Comments

I'm currently working my way through this book, I'd also have to recommend the Design Patterns. Although, the Design Patterns book is strictly on coding patterns Singleton, Factory, etc etc. I believe it has a good bit on Prototypal inheritance, which is what I originally bought it for. I referenced it many times when building my applications. In fact, it was so good the car jackers nabbed it from my car while I was on vacation!

15,902 Comments

@Drew and others,

Incidentally, the Javascript Patterns book talks a lot about prototype inheritance and "classical" inheritance and the differences between the two. Stoyan covers a whole bunch of examples of compromising solutions and their costs/benefits.

5 Comments

One of the "sneak peeks" from MAX was typography for the IDE. I hope Adobe continues to work on this; it was pretty sweet to see the editor adjust font-weight/color/size for function names, italicize arguments, put in horizontal dividers at obvious points, etc.

5 Comments

@Eric, That is funny because I thought that was the most worthless feature i have ever seen :)

I saw that and thought, who told them there was anything wrong with my editor to begin with?

15,902 Comments

@WebManWalking,

< and > should work (they'll get escaped) - unless you try to use Bold, B, Em, or I - I think those might always get evaluated. Although, I think I may actually strip out the CODE blocks before I replace the Strong/Em and then insert the CODE blocks back in.

26 Comments

@WebManWalking,

Love it. I'm of the same school. Although with IDE's that handle highlighting the associated end bracket it's of less of an annoyance to me when it doesn't happen.

What does really bug me are multiple conditionals for an IF that all get crammed into the same line.

3 Comments

It's encouraging to see PubSub or similar is becoming a staple JS design pattern.

"plan to throw one away"
is one valid approach, but there's also the Extreme Programming idea that no-one ever really does throw things away, so just do a quick spike session to play around with ideas, but once you begin doing several days of works, that's the real thing.

BTW there's some interesting work on patterns for development processes, e.g. http://www.amazon.com/organizational-patterns-agile-software-development/dp/0131467409

15,902 Comments

@Michael,

The whole agile approach to programming is definitely very thought provoking. I can't say that I know enough about it to really form any solid opinions; but, I think whether we acknowledge it consciously or not, once we start to write a lot of code, I think we tend to avoid removing it, even if we are open to the idea.

I know at work, if someone asks me if changing a part of the software is a good idea *for the user*, I'll occasionally say things like:

"I'm too close to the code to answer that objectively."

Meaning, I know I am now, at that point, too biased by the amount of code that has been written; as such, I am an unable to think freely as to whether or not a feature is a benefit for the user or not.

That said, I know a lot of people who try agile programming absolutely swear by it.

1 Comments

Ok, I am sold. I will buy the book~

I found your blog post as I am sitting here struggling with the urge to 'throw away' my first draft of the project I am working on. I feel like this is something that I battle with personal and business perspective.

I want to give my clients the best possibly product I can deliver but find myself battling with the timetable of when to stop and start over and still maintain deadlines. Also I get this feeling in my gut like I failed if I hit delete on the whole file and start over, so I am probably stalling longer then necessary and closing the window on myself.

I often find myself stuck in the middle, a sort of unstable ground where my files are filled with pasty code from several different evolutions of problem solving. I do wind up finding the best solution, but am trying cascade the solution back through the code I have written instead of starting fresh.

I look forward to this read and thanks for sharing :)

1 Comments

Hi.. nice to read your article. I have question about JS design patterns. I read about this pattern and some of them I understand about the flow logic.

But one thing that I haven't understand after I read about it is: when we use one of those patterns and why

I plan to create custom JS API/lib (like jQuery style) for my company that I worked for since it will be needed for a project, so which one is the best design pattern for that? is there any link for example?

by the way is your site/name any related with Ben Alman? hehe :D just a stupid question :P

Thank you in advanced :)

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel