Friday, September 4, 2015

A Plug for the JavaScript Jabber Podcast

By RCPanos

This is a quick plug for a very well-produced podcast on all things Front-end Engineering.  Although its named “JavaScript Jabber”, the team addresses many other topics that are related to producing great code such as testing, agile development, team dynamics, HTML5 and wild concepts like “Working from home.”  (I am a bit of a fan of said concept in moderation)

The format is simply a handful of accomplished software engineers (generally of BYU fame) interviewing an area expert.  Some of the guests are very heavy hitters, particularly their Robin Williams of frequent guests: Yehuda Katz. The key reason I enjoy their model is that the show is a discussion and not a lecture.

The other strength of this show is that the de facto host (Charles Max Wood) is a highly skilled full stack developer that has NOT made JavaScript his focus and his common side-kicks (Jamison Dance and AJ O’Neal) are of similar technological leadership ilk.  I believe this brings a lot of intelligent questions to the show as they all have the expertise to discuss costs and benefits.  They also simply aren’t afraid to look ignorant.  The team occasionally even gives some pushback to the experts.  Effectively, they represent listeners of many different skill levels and get to the key information out quickly.

This excellent podcast also heavily portrays a concept that I think many people overlook in our industry: Opposing viewpoints.  It’s unfortunate, but many intelligent software engineers think in terms of “the right way” or “the wrong way” when in reality there are trade-offs to many acceptable solutions.  I especially loved to hear a demigod of design decisions (Nicholas C. Zakas) assert that in some cases, all sorts of coding practices are acceptable as long as the whole team generally follows the same set of practices.

So when you are commuting or exercising, I appeal to my fellow developers to engage in a form of hyper- multi-tasking by listening to this show.  You will set yourself apart at your work place by learning a lot more than the latest buzzwords.  After listening to an episode, you should be able to speak to the tradeoffs for a given technology so that you can contribute to future design discussions.  As this insight would normally take days (if not months) of your own time to establish, this is 40-50minutes of time well spent.

Monday, August 3, 2015

The Ten Minute Overview of Drawing in HTML5

SVG and Canvas Tags


Due to some very intriguing conversations over potential future projects, I have been very motivated to dive into the world of “drawing” in HTML5 and I would like to share the high-level view.  So the following is not an in depth look at graphics frameworks but rather is a concise yet comprehensive perspective of the two incredibly awesome drawing tools available to front end developers: canvas and SVG (Scalable Vector Graphics). Oh, if only we had these tools ten years ago . .


The Similarities: Drawing


So before we go into all the differences, what do these two “new” tags have in common?  Well they both allow a developer to “draw” programmatically and they both are supported by all modern browsers plus IE 9 and above.  Animation is quite possible in both but there are clear advantages to either choice in different contexts.  The canvas API is directly manipulated using JavaScript while JavaScript can be (and often is) used to manipulate the XML structure that is SVG.  They both also come in pretty colors.  

So basically, the two tags have little in common but that they both “draw.”

The Differences: Many


Core Code Structure 

The most fundamental difference between SVG and Canvas is how they are stored by the browser.  Canvas is simply a bit map and its JavaScript API helps you update all the lovely bits.  This is useful when utilizing complex images (like from a Photo!) and allows you to save the image programmatically using the “toDataURL()” function.  However, this requires a lot of bookkeeping and can be very slow when you are managing a “large” canvas.


In contrast, an SVG graphic is communicated to the browser using a specific XML format describing an object model similar to HTML as it uses hierarchical system of elements with styles and attributes.  This XML could be loaded from the server or there are many libraries that will help you build this XML on the fly.  So unlike Canvas, SVG could be used without JavaScript, but that would eliminate much of its flexibility.

Core API

So really, the difference is not JavaScript (Canvas) vs XML (SVG) because you are probably going to use a JavaScript based library or at least your own scripts to manipulate the SVG XML as well.  However, it’s important to note that the core APIs set out by the W3 consortium are quite different for both.  Please note one reason there are so many SVG JavaScript libraries is that the core API is on crack:


Meanwhile, there is reduced crack usage for Canvas:


Relationship to the DOM

But don’t let me gloss over one of the most important advantages to SVG.  With a graphic drawn in SVG, each element is truly a part of the DOM.  So by simply grabbing reference (ID/Class) to some node within the SVG XML, you can, amongst other things, actually receive user events.  In contrast, a Canvas element is really just a part of the DOM in its totality so you have to use alternative methods to determine if one part of the canvas was clicked vs another such as floating divs over the canvas area.  So, if you need the user to interact with your graphic, there would be many advantages to using SVG.[1]

Resolution Considerations

Another major advantage to SVG is that it will have the same quality at any resolution because it is based on vector graphics.  The arcs, points, lines and other “geometric primitives” will have the same relations to each other no matter how much you “zoom” as they are resolution independent.  Meanwhile, the canvas tag is considered a raster graphic because it is based on a bit map and is therefore resolution dependent.  So if you are going to be adjusting the size of the given area that the graphic tag is rendered in, there might be some serious advantages to SVG.

Animation

The differences between raster and vector graphics also affect the ability to animate.  I have not done enough research to address the topic of animation in totality with these two tags but let’s consider the basics.  In general, canvas is considered better for animation because the “fire and forget” updates to the bitmap require very little processing.  However, that is assuming the actual amount changes to the bit map are relatively isolated.  In contrast, if you are changing a graphic representing half of the full screen, you might be better off using SVG because you would be updating millions of bits otherwise.  Its important to remember that processing requirements of SVG have nothing to do with the actual size (again, it is resolution independent) but instead is a product of the number of elements and their dependencies that would need to be updated.  So some articles refer to SVG having “medium animation” abilities and I am surmising this is because using simpler graphics in certain circumstances provides significantly better performance.  But Canvas is given the label “high animation” abilities because the more common scenarios require little processing time from the raster graphics format and is the much better choice.

All the Rest

The remaining factors you might want to keep in mind is that :

  • Canvas has a 3D “context” (mode) available
  • Text rendering is higher quality in SVG, but there are many reasons to use text in Canvas (see many of the Memes you see online)
  • SVG is properly layered while you’d need two separate canvas tags to have a layered effect

Conclusion


So I hope you agree that both Canvas and SVG tags offer tremendous graphics capabilities to the front-end developer.  Neither one is superior but both have different advantages.  So for your most advanced needs, you might want to consider using both!

See also:





[1] Although some canvas based libraries will help you work around these challenges such as: http://kineticjs.com/

Sunday, February 9, 2014

BackBone vs Angular, an original comparison

The following gives my take on the trade-offs between backbone.js and angular.js using an analogy to early web frameworks.  This includes factors of:

  • Flexibility and the opinionated factor
  • The Infamous Learning Curve
  • The Effects of the Open Source Community
  • Debugging Ability

Please let me know what you think in the comments below. 

I recently spent 6 months on a team implementing a very intense project using backbone.js (and marionette.js) to create  a very elaborate gaming market place.  It involved many of the challenges that a typical backbone project entails such as endless sub-views, animation, and handling click happy user events (gamers need to settle down.)  And now I have spent the last few weeks building sample projects using BackBones greatest rival: angular.  In doing so, I have become quite fascinated with vast differences in the cultures of the two communities.  So in order to articulate my own take on the choice between the two, I would like to suggest a new analogy for those less familiar with both:

BackBone is to early LAMP as Angular is to (rather) early J2EE

If you have been writing web apps for many years so that to you remember what it is like to develop the early Perl/PHP CGI scripts of say ~1997-2002, that will help.  But for those not from the web stone age, please let me explain.

Flexibility and/or Self-imposed Chaos

In the beginning, the libraries for Perl and PHP in this era gave you tools so that you could access the HTTP headers and send the appropriate responses, but to say they were opinionated would be the farthest from the truth.  They were exteeeeeeemely flexible so that you were able to shoot yourself in the foot on an almost hourly basis, thereby making giving your boss (Wad up Tannaz!) a reasonable effort estimate almost impossible.



Similarly, I argue that backbone gives you some solid guidance, but the fact is you can usurp that guidance at any moment with very little effort.  Meanwhile in Angular, with its system of dependency injection, the strict system of scoping, and the separation of services, the paradigm encourages you to think through all forms of abstraction.  So unlike Backbone, this does “force” you into some solid patterns and practices that will help you avoid chaos.

Back to my analogy, PHP (especially then – not so much now) and Perl also let you do almost anything you wanted even though you should show self-respect and follow SOME proper coding practices (can you say,  “code interpolated from variables?[1] “).  So having angular encourage or even force more structure is a lot like what J2EE did for web applications ~2002.

Learning curve

During my IBM internship in 1997, one of the countless Cal Poly alums (SLOTown!) handed me a book and I just started (horribly) cranking on my first Perl CGI script (OW, my foot!).  Meanwhile, learning Java by itself just from a book [2] was not easy, let alone learning J2EE.  Even in 2002, you really did need to learn a huge chunk of the API just to get by but there was no such list for early LAMP. So admittedly, I utilized two company sponsored classes back in 2002 just to get my first “promotion” into the J2EE team.  This is also a very common criticism of Angular, that it will take a lot more effort to learn because it is much more involved offering.

Open Source vs Controlled by the GOOGs

Another similarity here is that ten+ years ago the open source community seemed to strongly prefer the LAMP world to J2EE.  This is probably because it came first and possibly also because Sun Microsystems wisely kept the underlying standard of J2EE under tight control through-out its history because, apparently, they did intend to make money off of it (I never completely understood how).  In contrast, PHP was graciously given over to the open source community by its brilliant creator (Rasmus Lerdorf) very early and this is probably another reason the open source community has built so many frameworks, CMSs, shopping carts, and countless other forms of reusable tools with it.  Similarly, proponents of the BackBone world promote the long list of plugins and extensions available as reason for its superiority.  Meanwhile, the list of reusable components written in angular might never match the backbone list due to the differences in history and culture of the two communities.

Debugging

For reasons related to the above, I also see a similarity in debugging.  Many argue that Backbone projects are easier to debug because it is much easier to trace or console dump the un-minified backbone code itself.  You are free to do this in angular as well, but a common criticism is that the declarative nature of angular’s directives (markers on a DOM element) make this a much greater challenge.  My memory is that diving through all the open source code in LAMP is much easier than, say, diving through the supporting code of JSPs.  Also, I recall one of the great discoveries of switching over to the Java world was that the official error messages were so much more helpful.  I should not speak for the LAMP world over the past ten+ years, but I will declare that Backbone’s error messages are often terrible.  If they tell you anything at all, the information is rarely useful.  Meanwhile, I am adding powerful error messages to the list of reasons that I am grateful to the Angular team at Google.  It’s like these people have been on the app-building side of this equation before.  Crazy!



Conclusion

To sum up, the backbone and angular communities have some cultural contrasts similar to many other long standing debates in the application development communities.  Primarily: How much control does the developer want OR how opinionated do you want your framework to be?  I completely respect the developer that wants to feel a sense of invention and hates the idea of having to work around a paradigm that is restricting his or her creativity.  If that is your primary driver in being a developer, than please take from this analogy that you probably belong with the freedom crew and backbone.  I myself hope to still be a part of that crewe from time to time.  However, from almost my very first angular project, I was astounded as to how much I did not have to build on my own.  Angular, like J2EE years ago, just covers so much of the boilerplate code for me.  Meanwhile, during my backbone project, we were constantly re-factoring our code.  So if you choose angular, in many cases you will quite simply get a whole lot more done.

[1]   Ok Javascript can do that too but why? Really. Why?
[2]   Yup actually, I am that old. I was the last semester at Cal to learn Data Structures with C++.  Wow.  Someone buy me a cane . . .
[3]   But as I mention in my fist post, I encourage you to use a backbone framework (especially Derick Bailey's Marionette or possibly thorax by WalmartLabs).
[4] Pls see my first post for why Backbone is not a framework by itself

Sunday, October 20, 2013

The Ultimate BackBone Crash Course

Part one:  the 30,000 ft view

The following is an extremely simplified and slightly snarky synopsis of the popular Backbone JavaScript “framework.”  I hope to give a high level view of:
  1. What Backbone.js actually is
  2. What is in it
  3. Where to go from here
But in short, this is written for those brand new to the very powerful JavaScript toolkit so that they will have a high level view of what it offers before being tempted to dive into the incredibly joyous dearth of information that is the official backbone documentation.


What is Backbone.js

Backbone is often referred to as a JavaScript "framework" but it is not a framework like the other 3 leading frameworks[1] are in that it will not tell you exactly how to use it.  It is officially a library but that might imply it is as vast as one of the libraries it is built on, Jquery.  So I contend, it is really a toolkit consisting of a handful of powerful classes that might serve as the brains of your of the monster you want to build while also facilitating a pub-sub system to serve as the joyous nerve center of said monster.  In fact, I am pretty sure that is why it was called “backbone.”

That and, if you plan to only use this "framework" and not invent any of your own conventions to properly design your own system, then your evolving beast will likely become a weak and vulnerable beast waiting to be eaten by the evils of long term maintenance.


So farcical analogies aside, what exactly is backbone.js?

Backbone is a JavaScript toolkit that facilitates a type of  MVC(kinda) . .  & R . . with an A&E .. architecture. 

By that, I mean that Backbone provides the base classes you might use to follow the well-known MVC (Model View Controller) architecture  . . . except it does not officially have a controller.  Much of those official roles are often covered in the View classes.  But it does have a Router that serves some of the official Controller functions, thus it is actually an example of the trendy MV* (a.k.a. M-V-Star) architecture.  However, many who use backbone often feel the need to implement their own Application level object(s) and we cannot forget the high speed bus of backbone to organize its pub-sub methodologies, the Event class.  So Backbone.js a little more than a way to facilitate MV*.

Therefore,  I am dubbing backbone an MV*ea (or M-V-Starry) JavaScript Toolkit.

I realize you are now tremendously impressed with my ability to create new terminology, but I dare you to unlearn that mnemonic.  I dare you!


So let’s discuss this short list of powerful classes and the primary purposes they serve.


What is in it

The “Model” of the MV* software architecture pattern within Backbone is made up of model objects and collection objects.  Instances of the model are largely dumb objects that might manage some of your most basic ajax calls and they also initiate themselves in a clever manner.  But they really just hold data.  The collection objects are made up of a list of the same model objects instantiated from the same class.  They are also just a tad bit shrewder than models and are a more likely location to house code that retrieves large amounts of data from the server through the “fetch” or “sync” calls.  This is also usually the best place to abstract any browser side filtering of said data.  As these classes often reflect your data structure on the back-end, they are easily organized and often well contained.  However, in contrast, the View classes are usually a complete mess.

The View classes, of course, manage all the logic of displaying the UI ideally through the use of templates.  As Backbone is built on Underscore (which is built on JQuery) there are a couple standard templating systems easily available.  However, the View objects also must manage the events originating from the user and dynamic updates to these templates.  In plain Backbone (IE: not using a framework like Marionette), some Views often have to manage other sub-Views. This can get very confusing and lead to a lot of repeated “boiler-plate” code.  So to sum up, View classes do a whole lot and it is quite easy to make a complete mess out of said classes.



Fortunately Routers are quite simple.  They map a URL, including any parameters that might be involved, to one specific function often called an action.  These actions often involve creating Models and/or Collections plus initiating the server communications needed to be sure these pieces of data are valid.  These objects are then passed to new View instances.  So in most cases, the routers are the masters of instantiation.

Please note that how you organize the Routers is really up to you.  You could have one massive router for the whole system or you could have one router for every major server interaction in your system or every step in your workflow.  However, it often makes a lot of sense to organize your actions into different routers analogously to how you organize your workflow.  Life is just so much simpler when you know where everything is.



Lastly, Backbone provides a simple class to handle messaging (or pub-sub) within your system based on the Events class.  As long as one corner of the system is “listening” for the same message that another corner “triggers,” then you can manage responses to all sorts of actions at any given time.  This is especially useful when managing asynchronous events such as responses from the server or interactions from the user.

Please note Events are an example of a “use at your own risk” type of tool.  For instance, it is very easy to create two contradictory responses to the same message or to initiate a response to an action long after the context is appropriate but we will save that discussion for some sort of “pitfalls” posting later.  My only suggestion is to have some guidelines set for your application's use of events or Spaghetti may come to bite you.



Where to Go from Here

So despite the fact that this post is rather short, this really does sum up all the major components of Backbone.js.  Obviously there will be many lessons to be learned from your first major project, which is why I hope to post a list of “pitfalls” to avoid at some point.  I should also admit that much of my time as a Backbone developer has been whilst under the protection of Derick Bailey’s Marionnette version of Backbone.  The many reasons that this more structured form of Backbone is completely bad ass will also be saved for another post, but it’s fair to say that those that are using backbone the old fashioned way will have a different perspective than myself.  In fact, I would appreciate any comments on my ramblings in the interest of knowledge sharing.

But most importantly, if you are not going to use someone else's framework, I strongly suggest you come up with at least some standards for how you are going to solve repeated problems.  If you don't know what problems I am referring to, please rethink your decision to not use a backbone framework.

This author would like to thank his Cousin John Cardoza (AKA the Nevada Traveler) for teaching him to be snarky whilst writing on obscure topics.  Rewqls.




[1]Conversations in Silicon Valley generally give BackBone, Ember, Knockout and Angular credit for the top four spots in the charts.  If you disagree, pls comment below.