Showing posts with label intellectual horsepower. Show all posts
Showing posts with label intellectual horsepower. Show all posts

Tuesday, January 24, 2017

Don't Get Whomped by the Willow: easily building an object tree

One of the things I've needed to do on occasion is merge objects into a single tree based on a string that gives a position. It's not necessarily the easiest thing to do, because while it's possible to move down the hierarchy, that's only useful in reading the object, not in writing the object.

Rather than spend a lot of time discussing the theoretical, let's dive right in, working with an example.

Let's assume you have several objects, like so...


JavaScript - Defined Objects

var json0 = {       cgi_var_name: 'field',       label: 'value (Level 0)'     },     json1 = {       cgi_var_name: 'root',       label: 'root (Level 1)',       structure: 'root'     },     json3 = {       label: 'bar (Level 3)';       cgi_var_name: 'bar';       structure: 'root ~ foo ~ bar'     },     json2 = {       label: 'foo (Level 2)';       cgi_var_name: 'foo';       structure': 'root ~ foo'     },     json4 = {       label: 'snafu (Level 4)',       cgi_var_name: 'snafu',       structure: 'root ~ foo ~ bar ~ snafu'     };


...and you want to merge them into a single object, like so...


JSON - Our "merged object" goal

{   cgi_var_name:'field',   label:'value (Level 0)',   root: {     foo: {       cgi_var_name:'foo',       label:'foo (Level 2)',       bar: {         cgi_var_name:'bar',         label:'bar (Level 3)',         snafu: {           cgi_var_name:'snafu',           label:'snafu (Level 4)'         }       }     }   } }


Why might you want to do this?

One case might be that your ReST API is parsing JSON and expects an object that is further manipulated and processed before being returned. Unfortunately, an HTML FORM object is flat - which means your [insert your favorite framework here] representation likely is as well. For example, you could stringify your Angular scope object, but unless you've built a mechanism to handle it, it would never pass a tree to the API.

In order to merge these five objects (json0..json4) into a single congruent object, we have to climb both up the tree and down it...and here's how...


JavaScript - objMerge

function objMerge(field, path, base) {   var keys = field[path] ? field[path].split('~') : [ ],     ndx = keys.length - 1,     idx = 0,     deep = 0,     merge,     obj = { },     o = { };   for (idx = 0; idx < keys.length; idx += 1) {     keys[idx] = keys[idx].replace(/^\s*|\s*$/g, '');   }   obj[field.cgi_var_name] = field.label;   while (ndx > -1) {     if (base instanceof Object) {       merge = JSON.parse(JSON.stringify(base || { }));       for (idx = 0; idx < Math.min(ndx + 1, keys.length); idx += 1) {         if (merge.hasOwnProperty(keys[idx])) {           merge = merge[keys[idx]];         } else {           break;         }       }       idx -= 1;     }     if (idx === ndx) {       o = { };       o[keys[ndx]] = Object.assign({ }, merge, obj);       obj = o;     } else {       o = { };       o[keys[ndx].replace(/^\s*|\s*$/g, '')] = obj;       obj = o;     }     ndx -= 1;   }   return Object.assign({ }, base, obj); }


As you can see, we start fairly simply by splitting the structure into keys (the delimiter in line 2 isn't really important - it could be anything) and in lines 10-12 we trim those key strings. At this point, I'm going to need to call out line 14 - this is where I have special code tied directly to the object structure in my example, and for this reason you will need to modify this section. If, for example, you wished to merge complete objects rather than simply a few properties of the object, change line 14 to obj = field.

From there, we move on to the meat of the function. We can only build an object from a child up to the parent, because we only know about the child we're working with at any one minute. The problem is that we don't know if our current child has any siblings. Which means that before we define the parent, we have to look for it in the base object - which is what the code does in lines 16 to 27. The code loops through the 'lineage' looking for the keys in the order they're defined in our structure. If it finds the appropriately named ancestor, it tracks it as a good branch (or relevant level) and continues on to the next level.

Once we've identified whether or not we have a relevant branch, we can then either merge our child into the identified parent (using Object.assign) or declare a new parent for our child (lines 29 through 37). Once that is done, we go to the next level up and repeat the process.

Wrapping all this in a function means that I can write code that merges two objects into a single ancestor object relatively easily. Using the example code, I can call the function and pass in the object I want to merge, the name of the property that contains the path to the node where the object should be merged, and the object the object should be merged with, like so...



var scope = { }; scope = objMerge(json0, 'structure', scope); scope = objMerge(json1, 'structure', scope); scope = objMerge(json2, 'structure', scope); scope = objMerge(json3, 'structure', scope); scope = objMerge(json4, 'structure', scope);


...and the objects are merged, returning, in the final step, an object as described in the "merged object" JSON that describes our goal.

As usual, there are several ways in which this could be easily modified to meet other designs. For example, there is no reason the path string needs to be in the object being merged - it could easily exist outside the object - and the merge candidate identifying loop (lines 16 through 27) could be modified to identify another merge point. This example is intended to demonstrate how to merge two objects at different points on identical paths.

If you simply have two objects that need to be merged, you could attempt to merge them using Object.assign - but that doesn't always work the way you'd anticipate. A better option is to use code like this...


JavaScript Object Merger

function merge(source, base) {   var prop;   for (prop in source)     if (source.hasOwnProperty(prop)) {       if (base.hasOwnProperty(prop)) {         base[prop] = merge(source[prop], base[prop]);       } else {         base[prop] = JSON.parse(JSON.stringify(source[prop]));       }     }   }   return base; }


This function - merge - will loop through all the properties of the source object and if the property exists in the base object will recursively call itself to set the value.

Since all the code is present in this post, you should, as always, feel free to use this as you will, keeping in mind that you should always, as they say, "trust and verify"...and

Happy coding.

Thursday, December 22, 2016

Watching the Children

One of the things I've been working on is an AngularJS component that groups elements into a single field...which I thought would be simple. As it turned out, I learned more than I thought I would.

First, let me describe the scenario. The original block of code, that came out of a collaboration between designers and front-end developers, was inadequate. Here's what the code was (sort of) like...


Original Angular Markup

<div class="row">   <label>{{fieldLabel}}</label>   <select name="{{id}}_day" ng-model="day">     <option ng-repeat="option in ::days track by ::$index">       {{option}}     </option>   </select>   <select name="{{id}_month" ng-model="month">     <option ng-repeat="option in ::months track by ::$index">       {{option}}     </option>   </select>   <select name="{{id}}_year" ng-model="year">     <option ng-repeat="option in ::years track by ::$index">       {{option}}     </option>   </select>   <tooltip ></tooltip> </div>


Looking at the code I immediately knew that this was not written by someone who was familiar with several concepts every engineer must keep in mind - remember, we are getting paid to think - things like flexibility for localization, and more importantly, accessibility.

My first lesson

My first thought (beyond the obvious lack of accessibility practice, like having a linked label) was "why are they not using an input with a date type attribute". When I did some accessibility testing of my own, however, I learned that the user experience with an HTML5 date type input was far below what I would consider sub-par. Sure, the HTML5 date type has a better visual experience, but if you're relying on something like VoiceOver™ it's very unclear how you're even supposed to interact with the input. If you're relying on VoiceOver™, you'd have a much better experience if the input format (e.g., year/month/day or year-month-day) were described and you were left to enter it in a text type input.

Granted, from an accessibility standpoint there is little we could do that would not improve the experience. I was, however, limited in options - I had to retain the dropdown lists with the only label associated with the group as the primary (visual) interface - so I started where I could. After the first pass - to address the accessibility issues - the code was a little better, even if I did have to add a method to the scope object to set the date value using the three date parts. (Ok, I didn't have to add that, I could still pass the date parts, but adding it and gives me a single point of reference for the date, making validation and other stuff a little easier.)


Accessible Angular Markup

<div class="row">   <label for="{{id}}">{{fieldLabel}}</label>   <input class="visually-hidden" id="{{id}}" name="{{id}}" type="text">   <div aria-hidden="true">     <select name="{{id}}_day"      ng-change="setDate()"      ng-model="day">       <option ng-repeat="option in ::days track by ::$index">         {{option}}       </option>     </select>     <select name="{{id}_month"      ng-change="setDate()"      ng-model="month">       <option ng-repeat="option in ::months track by ::$index">         {{option}}       </option>     </select>     <select name="{{id}}_year"      ng-change="setDate()"      ng-model="year">       <option ng-repeat="option in ::years track by ::$index">         {{option}}       </option>     </select>   </div>   <tooltip ></tooltip> </div>


Although I won't delve into the tooltip directive here, I also made sure it had the ARIA role "status" so when the date was invalid (like a Date of Birth less than 13 years ago for Facebook), I could put that in the tooltip and it would announce to anyone using assistive technology as well as being displayed for anyone.

My second lesson

With the majority of the accessibility issues fixed, I moved on to improving the interface in other ways. There was a significant problem in that the order of the SELECT elements was fixed even though the day-month-year pattern applies to only a few cultures. The directive, as it was coded, would not be flexible enough to handle different formats - different ordering of the date parts - that are common across the globe.

Also, to improve the interface, it would be nice if the number of days were automatically adjusted based on the month and year. Not only does it reduce the cognitive load for poorly labelled elements, it reduces the number of accidental invalid dates like February 30th. Since Angular has two-way binding, and a way to watch properties in a scope for changes, this little modification should have been fairly simple. The good news is that it was. All I had to do was add $watch to the month in the directive and modify the days...oh, and $watch the year as well to account for February's 29th day in leap years.

With the ability to watch the year and month for changes and because JavaScript already has pretty slick slicing and dicing methods for arrays, modifying the number of days was easy peasy, and using days as an array on the scope also meant that passing that array into the ng-options attribute, made perfect sense.

Since I wanted to be able to pass the months array in (to ease localization) this was the perfect time to make that little switch and add a date format to the scope that enabled me to switch around the order of the dropdown lists. A little parsing of the date format that was passed in and I have an order property on the scope that I can use for another of Angular's features - ng-switch.

After these little changes, I had something that looked like this...


Localizable Angular Markup

<div class="row">   <label for="{{id}}">{{fieldLabel}}</label>   <input class="visually-hidden" id="{{id}}" name="{{id}}" type="text">   <div aria-hidden="true">     <ng-switch on="::order[0]">       <div class="datepart" ng-switch-when="d">         <ng-include src="'dd.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="m">         <ng-include src="'mm.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="y">         <ng-include src="'yy.html'"></ng-include>       </div>     </ng-switch>     <ng-switch on="::order[1]">       <div class="datepart" ng-switch-when="d">         <ng-include src="'dd.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="m">         <ng-include src="'mm.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="y">         <ng-include src="'yy.html'"></ng-include>       </div>     </ng-switch>     <ng-switch on="::order[2]">       <div class="datepart" ng-switch-when="d">         <ng-include src="'dd.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="m">         <ng-include src="'mm.html'"></ng-include>       </div>       <div class="datepart" ng-switch-when="y">         <ng-include src="'yy.html'"></ng-include>       </div>     </ng-switch>   </div>   <tooltip ></tooltip> </div>


Included Markup Files - dd.html

<select name="{{id}}_day"   ng-change="setDate()"   ng-model="day"   ng-options="days.indexOf(day) as day for day in days"> </select>


Included Markup Files - mm.html

<select name="{{id}_month"   ng-change="setDate()"   ng-model="month"   ng-options="months.indexOf(month) as month for month in months"> </select>


Included Markup Files - yy.html

<select name="{{id}}_year"   ng-change="setDate()"   ng-model="year"   ng-options="years.indexOf(year) as year for year in years"> </select>


Using this ng-switch pattern with parsing code similar to...


Format Parsing

var format = (/^([ymd]*)\W?([ymd]*)\W?([ymd]*)/i)        .exec($scope.dateformat).slice(1, 4); $scope.order = [   format[0].replace(/y+/i, 'y').replace(/m+/i, 'm').replace(/d+/, 'd'),   format[1].replace(/y+/i, 'y').replace(/m+/i, 'm').replace(/d+/, 'd'),   format[2].replace(/y+/i, 'y').replace(/m+/i, 'm').replace(/d+/, 'd') ];


...in the directive means that even a two-part date format, like month/year, will be displayed correctly, and you can use the same datepart identifiers as are used in Angular's date filter.

Third lesson

So now it was worlds better - accessible and ready for localization. That tooltip, though, was going to give me fits. Getting it to display when the input had focus and hide when it didn't was easy...but the SELECT elements are not siblings of the tooltip (preventing CSS from working) and the focus event doesn't bubble so I couldn't add a listener to the element containing the SELECTs that was a sibling to the tooltip. To make matters worse, in Angular, the focus event doesn't fire for a SELECT element until the change event fires. It was like some grand puzzle preventing me from getting the tooltip to hide and show when the focus was on any one of the date parts.

So, how did I solve this little riddle?

First, I thought to use $watch on the SELECT elements in some way. Of course the first problem in attempting that is that by using the ng-switch to help with localization I had prevented the SELECT elements from being present in a way that would allow me to get a hook into them. Add to this the fact that the focus event wasn't firing and I thought I was blocked...but then I remembered I was getting paid to think.

I added the onfocus and onblur attributes to the SELECT items in the markup to by-pass Angular. That fixed the timing problem - the onfocus and onblur fire immediately when focus or blur occur, not when the change event occurs, and I thought I could use them to change the class to indicate focus and use $watch in the directive to watch the class attribute of the SELECT. Unfortunately, that didn't work. Even though I was able to get the class to change by adding onfocus="this.className+='focused'" and onblur="this.className=this.className.replace(/\bfocused\b/, '')" to the SELECT tags, the element instance in the DOM was out of sync with the element instance in the directive. I knew the onfocus and onblur event handlers were key, though, because they allowed me to get the focus event without the change event.

Given that I had to figure out how to get the two references in sync, what I needed was a way to get the onfocus and onblur attributes to reference the directive scope. Referencing the directive scope wasn't enough, however, because I also had to be able to call $digest to get any changes to the scope made outside of Angular (which native event handlers are) recognized. To make that sync easier, I added methods to the scope - one to set a scope property (focused) to true, and one to set the same property to false - and this is key - made sure those methods also called $digest. Next, I changed onfocus and onblur to call the methods I had added to the directive scope in the SELECT elements, and then added the ng-class attribute to the DIV containing the SELECT elements to identify that the field had focus any time the property was true (i.e., ng-class="{'focused': focused}").


Included Markup Files - dd.html

<select name="{{id}}_day"   onblur="angular.element(this).scope().blur();"   onfocus="angular.element(this).scope().focus();"   ng-change="setDate()"   ng-model="day"   ng-options="days.indexOf(day) as day for day in days"> </select>

So, at this point, I was pretty sure it was all set...and, just like in the LEGO movie, everything is awesome.

So, there you go...a quick way to watch the children of a DOM element, sort of.

Happy coding.

Monday, October 3, 2016

Beyond the UI: Pitfalls and Best Practices in JavaScript

When I was asked to present at DevCon about JavaScript, there were a lot of things that came to mind - new things I was exploring that I found exciting and long-held beliefs I am generally eager to act as evangelist for - many of those were dismissed as I talked to the conference organizers and they asked that I "go back to basics" but somehow cover both user-agent JavaScript and JavaScript in Node. With that suggestion in mind, I came to this - the pitfalls and best practices in JavaScript.

A little research has revealed that 0.2 percent of web traffic is from user agents that either do not have JavaScript available as a feature or have JavaScript disabled. That means a whopping 99.8 percent of user agent traffic has JavaScript in the front-end. If we add back-end and middle layers that use JavaScript through things like node.js, it's pretty easy to see that JavaScript is everywhere.

While 99.8 percent of front-end traffic is from user agents with JavaScript enabled, it is still very easy to functionally disable JavaScript, and when that happens, everything from simple interactions to complex Single Page Applications fail, and can leave your users - your customers - staring at a blank page. That's not acceptable. That means we must write good code. How do we do that?

Writing code is a skill - which means it can be taught and practiced - and practice is really the only way we get better at any skill, but that's where we often go wrong.

My daughter studies Irish dance, and I asked her one day how she could get better so she could advance to the next grade, and she responded that her teacher told her "practice makes perfect". Seeing what we parents like to call a "teachable moment", I asked her what would happen if she practiced her dances, but practiced the wrong steps - what if she put the steps of her reel in the place of her light jig, for instance? Our discussion of the possible outcomes ranged from disqualification - or as she likes to call it, "getting a big fat zero" - to possibly winning a medal if the judge(s) didn't notice the difference.

That's when I told her that it's not the practice, that makes perfect - it takes more. It's perfect practice that makes perfect. It's not enough that she just practice - she has to practice the right steps, and that's how it is with writing good code. It's not a matter of how practiced we are, it's a matter of how much we've practiced the right things.

So, what are the right things when it comes to good code? Ultimately, good code is good writing. Yes, we're solving a problem, but if we look at it another way, we are telling a story about how to solve the problem. What are the elements of good code - the same elements as good writing.

Good writing has clarity and focus. As engineers who have built object-oriented code for two decades, we pretty much have the 'focus' element down - we just call it 'encapsulation'. Clarity, on the other hand, could use some work.

Good writing is organized. Back in day, we struggled against spaghetti code. We've gotten beyond that now, especially with event-oriented programming, where we have the very real threat of callback hell.

Good writing uses precise language. It says exactly what it means. Here, we can think about data types and how we speak or write outside of code. If you use the word biker in one community it may mean something entirely different in another, and likely does. That word, in a sense, refers to two different data types and is, unfortunately, not very precise.

Good writing uses correct grammar and style. Again, one of these - the grammar portion of the rule - we have down. The syntax is the syntax, and there isn't really a way around it. The style portion of the rule doesn't refer to your "personal style", rather it refers to the stylistic elements like how indentation and braces are used. Using incorrect style is something like dropping a comma from a sentence. We, of course, realize there is a big difference between "it's time to eat, grandma" and "it's time to eat grandma".

Good writing expresses the author's voice. This is your personal style - what makes your code different than code written by someone else. This encompasses things like which substring function you use or how you build a string - whether you use an array and join or the plus operator. These are the things we sometimes don't even notice unless they're vastly different than our own way of doing things.

Ultimately, it all comes down to one thing - we can describe good code in terms of how understandable the story is to other people, because "any fool can write code that a computer can understand; good programmers write code that humans understand".

Now, let's put these elements in terms of best practices that help us understand how we can achieve clarity and focus, how we might approach organization, what it means to use precise language, and what correct style is.

In the language of those who evaluate and manage risk, we hear about "known knowns", "known unknowns", and "unknown unknowns". After nearly two decades of experience with a language and millions of developers all over the world writing in it, we've pretty much identified all the gaps in the language. We often still struggle with where the gaps are in our applications. In a sense, we know that we're missing a piece of the map, but we don't really know what that piece of the map represents.

Is Sky Broadband familiar to anyone? Sky Broadband is a large Internet Service Provider in the UK, and in the early days of 2014, Sky Broadband mistakenly marked the subdomain code.jquery.com as malware - the entire CDN repository. Suddenly pages all over the UK stopped working - the user experience for literally millions of users was ruined, regardless of whether it was a simple interaction or a more complex application.

Of course this not only happens in front-end code, it happens elsewhere as well. It can even happen in Nodejs applications - anywhere JavaScript is used.

Earlier this year, NPM involved themselves in a brand infringment disagreement that was originally between a developer who had several published modules and an organization who wanted to use the name one of his modules used. After NPM acted, the developer pulled all his published modules from NPM, including the eleven lines of code published as 'left-pad'. When that module was pulled, thousands of projects broke before NPM restored the module.

We can debate the ethics around this second example, but in this case it's worth noting that it was eleven lines of code that padding a string on the left side. It wasn't a complex, multifunction library - its removal should not have broken thousands of projects.

You must always know not only what your dependencies are and where they are, but what they do. Put them squarely in the known unknowns column so you can guard yourself against the time when they disappear, or are blocked by an ISP, or are broken in the new release, or any one of the many things that can happen. Not fully identifying dependencies can result in a poor debugging and support experience as well as a poor - or worse, non-existent - user experience while you resolve dependency issues that arise, so the first item on the list of what will be ten principles is to identify dependencies.

We come to it at last. The great battle of our time. And it's the kind of battle few but engineers can have - a battle about design patterns. Make no mistake, nearly everyone takes a side in this battle, but it's no battle between the five armies and the forces of Sauron - there is no good side or evil side - just two competing ideas, each with advantages and disadvantages.
The debate between proponents of the Module Pattern and the Prototype Pattern can be severe; however, if you keep an open mind you will see that these patterns are not terribly dissimilar. The Module Pattern offers advantages in clarity that the Prototype Pattern does not - an advantage more pronounced in teams with greater history in Java development. The Prototype Pattern offers advantages in memory management and performance that the Module Pattern does not - although that advantage can be lessened by applying strict structures and development practices.

By keeping an open mind with an eye focused toward design concerns, you can more easily determine which pattern is appropriate for your needs. It may also be the case that one design pattern is used in a specific context and the other used in a different context; however, I would generally advise against such an arrangement due to the loss of clarity with the reduced consistency. Most importantly, however, the second item on our list of principles is to identify design concerns.

The next contentious debate - albeit one that has died down in recent years - is about indentation style. Years ago, when I was first writing code - about the same time the movie Highlander was released - the hot programming language was C and the indentation and brace style was called K & R - for Kernhigan and Ritchie and The C Programming Language. JavaScript, unlike other languages, has some quirks - different ways of handling control statements and white space and an implied semicolon, or automatic semicolon insertion, for instance. Unfortunately, this sort of behavior could lead you to lose your head if you're not careful, which is why every engineer with more than a modicum of experience with JavaScript will tell you to use the One True Brace Style, or OTBS - because there can be only one.

Here we'll take a look at some statements that use different brace and indentation styles. On the left you'll notice the if statement has no brace but the return statement is indented. In a language such as Python, this would indicate that the return should occur only when the conditional is true; however, in JavaScript the if statement without a brace will only consider the next newline part of the conditional, meaning the return statement will happen every time, not just when the conditional is true. The second example on the left side - the return statement - will get an implied semicolon, causing it to return null every time.

The examples on the right side show the same statements with the left brace on the same line as the control statement. This pattern is the One True Brace Style, and not only does it offer more clarity for the reader, it actually works the way you would expect without inserting semicolons where they're not actually present in the code.

Because of the potential for confusion, not just of humans but the computer as well, always use the One True Brace Style. If not, you may lose your head.

I have a friend - a JavaScript engineer - who is fond of the saying that there are always at least two developers working on a project, you and the developer you will be in six months. I know I look back at code I've written six months ago and say to myself "what were you thinking" or not, as the case may be. Was I confused or tired? More often than not I say to that other developer - me from six months ago - "I suppose you think that was terribly clever" and I think if I only had added comments in I would know just what was going on in the head of that other developer - the me from six months ago.

Comments, though, are only helpful when they're present, and it would seem that a lot of us don't really want to put them in. As a senior engineer at PayPal, one of my tasks was to perform technical interviews when there was a new candidate. I was surprised at the number of people who responded, when asked about comments, that they write self-documenting code. I was often a bit like Inigo Montoya - I don't think that means what a lot of developers think it means. Self-documenting code is code that is written with precision and a measure of clarity. Both of those are qualities of good code, but they are not enough.

You should never assume that self-documenting is enough, because as the six month older me can verify, it's not. It's not enough. Put comments in, and when you're adding comments, you'll want to keep two things in mind. First, always use the whack-star pattern, even for single-line comments. I cannot count the number of times I've seen otherwise beautiful code mangled by a minifier because someone used a whack-whack and a large portion of code that should not have been commented was. As an added bonus, if you use the whack-star pattern and combine it with a whack-whack while you are developing, you can comment and uncomment large blocks of code with the insertion or deletion of a single whack - which in our example would go on the line just after the function declaration before the whack-star, commenting or uncommenting the console.log statement. The second thing you'll want to keep in mind is to use the JavaScript version of JavaDoc - JSDoc. Not only does this offer clarity to your comments and code overall, the syntax is shared among the Java community and it eliminates the need to maintain API documents as a separate project.

The clarity offered by the inclusion of comments is simply too significant to ignore. Clear, precise comments will also help you organize your code and make that organization plain to other developers working on the project - even what that other developer is you. For these reasons, I've added "use comments" to the list of principles as item number four.


Not long after I started at PayPal, we found a bug in the checkout process. It was especially difficult to root out because all the tests in development passed and all the tests in the QA sandbox passed, but when we went to production things just didn't go quite as we expected them too - there was evil there that did not sleep.

Part of the difficulty in diagnosing the issue was the nature of web sites between development, quality assurance, and production. There are resource intensive features - like analytics - that we don't want on development or QA boxes and sometimes that means our production environment is best described the way engineers used to describe aircraft - a collection of parts in close proximity moving quickly in the same direction. If we add poor coding practices into that particular mix, the risk of failure is significant.

In our case, the error was eventually traced to a variable in our analytics package that was not in the proper scope. This previously unknown global variable in a dependency wrecked havoc until it was fixed. Take a lesson here - avoid global variables. In fact, as you can, avoid the global namespace altogether. Also, always use the var keyword when declaring variables - leaving it out will force the previously undeclared variable into the global scope, even if it's only used in one little function.

Third, declare variables at the beginning of the scope. Not only does this offer a little written clarity and orgnization, it offers conceptual clarity as well as it accounts for the hoisting that JavaScript does. Fourth - and this is as important as the previous three statements - call things by their name. If you'll recall, one of the elements of good writing is that it uses precise language. Calling things by their name is part of that precise language.

Fifth, and finally, define variables in the narrowest scope possible. It's not enough to just avoid global variables, define variables as narrowly as possible. Not only will this offer a degree of precision and clarity, it will help with memory management as well.

Now I'm going to combine these five steps into a single principle we can add to the list. We're going to call that principle "name and scope variables properly" and we're going to add it as the fifth item on the list.

At this point we're nearly halfway done with our list and we've still not talked directly about code - at least not more than using the var keyword - it's all been about the softer elements like style.

We've come quite far, though - all the way to Dagobah. Master Yoda - ever encouraging and training Jedi. Of course we know he's in the Star Wars universe and we're in the JavaScript universe, because for us there is a try - and catch - and finally - and we need to use them.

The try statement will be one of your best friends. Gone are the days when it wasn't supported - I believe WebTV was the last user agent that didn't handle it - so feel free to use it any time it's appropriate. It can be especially helpful when you have dependencies and you need to minimize the risk associated with them, because you can catch exceptions thrown when those dependencies are not present.

The try statement also gives you the ability to further customize your user experience. Within the catch statement you can determine the kind of exception thrown by using the instanceof operator as shown on the slide. One word of warning - you may see examples where the exception type conditional is wrapped in the parentheses of the catch statement - don't use that practice - it's not supported. When testing the exception, use the pattern shown here. If you wish to dismiss the exception, use ignore rather than err as the parameter name. It offers a degree of clarity that is also recognized by most linters.

As our sixth principle, then, we are to do the opposite of what Master Yoda says and use try - and catch - and sometimes finally. Speaking from experience, it really will save the user experience or, at the very least, allow you to fail somewhat more gracefully than you would otherwise.

Next we'll have a word about data types.

JavaScript is a loosely-typed language, which means the data type of a variable is not declared. As expected, sometimes engineers have difficulty with the lack of precision that typically accompanies loosely-typed languages, and the lack of strict types been one of the arguments engineers have used against JavaScript in the past.

Concerns about the lack of precision and clarity in loosely-typed languages seem reasonable. After all, you wouldn't want a doctor type if you needed an engineer, or vice versa, and we all know the difficulty Bones had - he had to remind Captain Kirk countless times that he was a doctor type and not some other type.

So let's take a look at a function - one that will be used again as we progress through our list - and see how it might instruct us or what we can glean from it to add to our list.

First, you'll likely notice that there are no comments - if only there had been comments we might have a clue what it is we're look at. Fortunately for us, it's self-documenting code, so we can see that the foo function is looping forward through a list of some sort - from the syntax it appears to be an array - and changing a property on each element of the array that's an object. Seems simple enough - there shouldn't be any problem at all, right?

Except there might be. Notice that on line seven we check to make sure the element is an object. We do that because we're accessing a property - in this case className - on line eight and if the data type of the element were say a number or boolean trying to access the className would likely raise a TypeError exception. Are there other types that would raise a TypeError exception? Sure - a null value would - but that's not an object, right? Unfortunately it is - the typeof operator returns object when the type is null. Line seven will have to be fixed.

Any other problems? As I mentioned earlier, it looks like the list we're using is an array, but we have no comments that tell us that and there isn't a type check to enforce that, we're just going by the square bracket used to reference items on the list. Look at lines twelve and thirteen. Using those lines we can see that the list we're getting is actually a NodeList, which is a live collection. Looping forward through a live collection incurs a significant risk of infinite looping…but there is no way for the developer who wrote the foo function to know that the developer who wrote the function call is going to pass in a live collection, and the developer who wrote the foo function didn't give any clues to the developer who wrote the function call that an array was expected.

Ultimately, we can see that this code is not nearly as precise as it should be. The engineer writing the foo function could have used item instead of square brackets, or alternatively checked the type of the list variable to ensure it was an array. The engineer should also have checked for other types rather than just relying on a type object before modifying properties. You must always keep data type in mind, otherwise your code is prone to serious errors - errors that will often be very difficult to find and correct.

The I, Mudd episode of the original Star Trek series is one of my favorites - mostly because of its use of logic, but also because of the phrases that seem to belie the seriousness of the situation - phrases like "we seem to be taking an unscheduled ride" - it's rather like "oh, it appears we've been taken hostage and may die, but at least there's tea". Infinite loops - like those triggered by looping forward through a live collection - are the unscheduled rides of JavaScript. They're a little humorous in that they're usually brought on by a careless mistake but they can really ruin your day.

I mentioned that we would return to the foo function, so let's do that now - but let's make some corrections to it in an attempt to fix the issues. First, we'll correct line seven so that we'll catch a null value that would raise a TypeError exception - we can do that by putting a truthy check in there. Next, we'll set the loop up to start and the end and loop backward to the beginning - if we're looping through a live collection or an array that's the safe way of doing it. We'll set the index variable to the length of the list and change our for loop into a while - it's faster anyway so bonus there. Now we're all set to go - we've modified the code so it's flexible enough to handle live collections and arrays without blowing up.

Sort of. There's a potential problem in our while loop, associated with the fact that we're using the index value - a number - in a truthy check. A zero value is false, but all other numbers are true - which means negative numbers are true. We're using a decrement operator on the loop index to move backward, but the operator is in front of the variable name rather than behind the variable name, meaning the decrement is performed before the variable is evaluated. If the list length is zero, the index value is negative before it's evaluated the first time, so the truthy value is true and continues to be true as the index is decremented, and your unscheduled ride is on in earnest.

There are ways we can compensate for this - ways we can avoid the unscheduled ride, but it's the simplest way that also adds clarity without losing precision in the language - and that's to avoid confusing operators, which you'll notice is now the eighth principle on our list.

You'll recall that our while loop in the foo function - while decrement index - used a number that was decremented before being evaluated and as a result, the negative number was treated as true and sent us into an unscheduled ride. This is ultimately because not only is JavaScript loosely typed, but it's also what I call type fluid. Variables change data types in one of three ways: they can be converted, which requires an explicit function call; they can be explicitly coerced, which typically doesn't use a function call but instead uses a clue or hint that we want the variable coerced; and they can be implicitly coerced, which is when one data type is directly treated as another type.

Other languages give the ability to convert between data types; however, JavaScript goes beyond that. In fact, it will often coerce values even when we are neither aware the value will be coerced nor want the variable coerced. In a sense, it's as if JavaScript says "we will convert your data type to our own, resistance is futile".

So let's take a look at a simple variable statement and see where the potential problems lie and use that to determine what principle we should follow to write good code.

Here you'll see we have the value for PI as a string in scientific notation. We then convert that string into a number using two different methods - Number and parseFloat - both returning a floating-point value, before we attempt to convert the value to an integer using parseInt or coerce the string using the plus and minus operators and finally coerce it from an ordinary floating-point to a fixed precision number.

Notice that four of those statements are identified as potential problems.

Let's start with the first potential problem - parseInt. One might assume that the number would be converted to a floating-point then converted to an integer; however, that is not even remotely the case. The conversion reads the string starting at the left and moving right to the first non-digit. Everything in that substring - here '0314' - is then converted to an integer. There's a hidden gem in this particular conversion method, however. If the left-most character in the string is a zero, the parseInt function - which has an optional radix parameter - may default to octal and convert 0314 to the integer 204. Suddenly, though you were expecting three, you have the number 314, or possibly 204.

Next, we look at the plus2 variable. In this instance, we have two different data types - string and number - but the code is not converting either of them; the code is, however, explicitly coercing one of the values - the question is which value will it coerce.

As you can see, the two was coerced to a string data type and added to the existing string, giving us a much different numeric value - one that is a mere fraction of the value of PI.

While I would like to be able to give a hard and fast rule that says the plus operator will always concatenate strings first - that it will coerce a number to a string and then concatenate it - it's not that simple. If the plus operator is at the beginning of the variable name without white space between the plus and the variable name, the value will be coerced to a number before other operations are performed. This is true even if the value is a boolean - which is a one when true and zero when false after it's coerced.

Next, let's look at the minus2 variable. In this instance, we again have two different data types - string and number - and the code is not converting either of them. The difference between this variable and the plus2 variable is the use of the minus operator in place of the plus operator.

We might assume, given the behavior of the plus operator in the plus2 variable, that the result would be the value of the pi variable with the two removed. Of course that is not the case - the minus operator does not split a string or perform any sort of substitution on a string variable. In this case, pi is coerced to a number and two is subtracted from it. You'll notice, however, that when the pi variable is coerced, the value is different - it's not 3.14. If you're checking equivalence of coerced values, you will likely be surprised.

Finally, let's look at the asDollar variable. Of course you would not be very likely to request a precision of eighteen when referring to a dollar value; however, this example is intended to showcase a particular problem. You may think, especially given the name of the function being called - toFixed - that you are simply requesting a specific precision, but you are not. If you'll notice, the string data types on this slide have been identified by, one, being enclosed in single quotes and, two, using an italic typeface. The value for our asDollar variable is enclosed in single quotes and uses an italic typeface. You thought you were asking for a fixed precision number, but what was returned was a string.

Coercion, both implicit and explicit, is problematic. It, at the very least, lacks clarity and precision. Because of the severity of the errors that may be introduced, I've added the principle "avoid coercion" as the ninth item on the list of ten principles.

With the ninth item having been added to our list of ten principles, it's clear that we're near the end, and at this point we're going to leave code behind.

After we've followed all nine principles, and we have well-commented, self-documenting code that is precise in language and structure it'll work without a problem, right? We can have total faith that what we've written will do just exactly what we want it to do the first time and every time. That kind of faith is fine with Lord Vader - who finds a lack of faith disturbing - everyone else wants you to test your code, then test it again before you test it again. Write and run every unit test you can think of and test cases you think are highly improbable, because especially if you do the amount of business that a company like PayPal does - which was nearly five billion transactions in 2015 - you can be surprised at just how often the highly improbable happens.

In addition to running every unit test you can think of and several you hadn't thought of, be sure to use a linter to verify your code - jshint, jslint, and eslint are all very good and all do basically the same thing but in different ways. Each of the three has its own interface and can be integrated into the development process at a different point. If you wish to use all three, that can be done - but it's a little overkill. I would suggest that you integrate a linter with your version management tool, and while I have no direct experience with it, I understand having a linter integrated with your IDE makes life significantly easier.

Third, minify your code and test again. Be sure here you're using the same aggregation and minification process you use when rolling your code out into production. Each process has its own way of accomplishing the task and each can introduce something special into the mix that will break your code. I've seen beautiful code mangled and crushed into an inoperable state by aggregation and minification.

Fourth, perform code reviews. Here's something else we tend to get a little bit wrong much like we do with the expression "practice makes perfect". Typically, senior team members review code before a pull request is approved to verify that the code is sound and adheres to whatever standards exist within the organization. Those are good criteria; however, code review should not stop there. Code review should include the most junior, least experienced engineers in the group. The practice of heavily involving junior engineers in the code review process gives them the opportunity to learn to code better - just like reading good writers makes a writer better - and it gives the authoring engineer confirmation that their code contains the elements of good writing. If your code does not have the clarity to be understandable to the least experienced engineer on your team, it is not clear enough. Here I should point out that the junior members of your team need not know how to code a solution to every problem - if that were the case they would likely be senior engineers - but they should be able to understand the solution they are reading.

Fifth, as part of this process, have a human test your peer-reviewed, unit-tested, linted, minified code. This step is extremely important for any JavaScript intended for a user-agent even though it may be decidedly less so for code that runs in Node. Basically, any time a human meets the code - whether that's in a user-agent or on the command line - test the interaction. Humans have quirks and habits that help them generalize experience and reduce cognitive load that will affect how they interact with the code. Simply put, in general, no two people will interface with code the same way. There will a lot of overlap, to be certain, but it's the edge cases that you're testing here - all those behaviors that are especially active when someone is interacting with a new problem - all those things that are highly improbable.

All five steps in this process have one thing in common - that one thing that Lord Vader finds disturbing - they show a lack of faith. We need to remember as engineers, however, that our realm is not what Han Solo called a "hokey religion" - our realm is one of facts and data and requires proof. Show a lack of faith in your code and prove that its good code and good writing.

So there they are - ten principles that not only help you avoid some of the most common pitfalls, but principles that will help you become a better writer as you make their implementation habit. Follow them, and you'll discover that not only does the computer understand your code, humans do too.


A Special Note

This is the extended version of the Beyond the UI session I delivered at the American Express Mobile-Web DevCon on 28 September 2016.

Thursday, July 14, 2016

Go Splunking

See the forest *and* the trees

There are more than a few analytics packages out there, and some of them give you pretty decent insight into business operations – called Operational Intelligence. There are a lot of reasons why C-level executives (and even those lower on the food chain) would want that insight into business operations. Our problem (or opportunity) then, is that when we (as UI engineers) are faced with presenting that Operational Intelligence in a dashboard, what do we do?

For this post, I'm going to focus on Splunk for a few reasons. First, it's pretty widely used – most people familiar with business analytics have at least heard of Splunk. Second, building stuff for Splunk is a lot simpler than it seems at first glance, as you'll see if you keep reading this post. Third, I have a personal relationship to it – at least two of the four companies I've worked with in the last five years use it and I've been privileged to review multiple tech books about it over the last five years, which has let me experience it through others.

Two of the most common approaches when developing dashboards or apps for Splunk are using Splunk's Simple XML and using HTML, CSS, and JavaScript on the Splunk server to develop the apps everyone wants. There's another option though, and it's the option I would suggest – develop the app on a completely different server.

Developing the dashboard or app on an non-Splunk server lets the Splunk server do what it's really meant to do – index data and provide a query interface to the indexed data – and lets another server handle user requests and serve up the adaptive, responsive web pages more easily and consistently. In addition to resolving potential performance and maintenance issues, this also enables you to create web pages that comply with all the web accessibility guidelines easily (which is something Splunk isn't great at, to be honest). If the tools you use to develop your Splunk dashboard/app are the same tools you use for your other web apps, there are even more benefits (such as possibilities for code re-use).

Here's a quick and (admittedly) overly simplistic explanation of how to get started and have a basically free server that responds quickly and keeps security in mind.
  1. Set up a web server using node.js
    For this you can use something like Express, but you might also develop your own. If you decide to develop your own, feel free to look at my node-experiments github repo at https://github.com/hrobertking/node-experiments. You'll want to use node.js for this (rather than using Apache or Nginx or something else) for reasons that will be revealed in the next step. For the purposes of this blog entry, I'm going to refer to this web server (which should really be dedicated to your Splunk apps) as the Splunk App Portal.
  2. Add the Splunk SDK (JavaScript version) to your toolkit
    The Splunk JavaScript SDK requires node.js for server-side scripting. Of course you can install it easily (npm install splunk-sdk) and then use require in your script to access it. As part of adding the SDK to your toolkit, be sure to visit the Splunk>dev JavaScript portal (http://dev.splunk.com/javascript) to see the SDK documentation, including examples.
  3. Instantiate a Splunk Service object
    Here's the relatively easy part
    var splunkjs = require('splunk-sdk'),   service = new splunkjs.Service({       host: 'my_splunk_server',       password: my_splunk_password,       port: 'my_splunk_server_port',       scheme: 'https',       username: my_splunk_username,       version: '5.0'     });
    Note that you should not ever code a username and password in a JavaScript file. If you pay careful attention to lines 4 and 7 you'll note that the values are not enclosed in single quotes – they are variables. Put in a little extra work and set the value of those variables from the command line. Using this approach enables your newly created Splunk App Portal to communicate with the Splunk server in a controlled manner. I also recommend establishing a Splunk account specifically for this purpose so that use can be monitored and controlled with greater granularity.

    I should point out that if you're using JavaScript to develop apps for Splunk another way, you're most likely adding the config.js file and calling the config method to pass in the username and password. It should go without saying (but won't) – don't hard code the username and password in JavaScript file. If you're doing something like the following, stop and fix it.
    <script src="MY_SPLUNK_FILES/splunkjs/config.js"></script> <script> splunkjs.config({     host: 'my_splunk_server',     port: 'my_splunk_server_port',     scheme: 'https',     authenticate :{       username :'DoNotDoThis',       password :'NoNotEver'     }   }); </script>
  4. Call the oneshotSearch method to get your data
    Calling the oneshotSearch method is fairly straightforward, code-wise, anyway.
    service.oneshotSearch(query, params, function(error, results) {     //your rendering instructions go here   });
    Here's where it gets a little tricky. The query argument will be something like 'search index=myindex'. If you have even the slightest experience with Splunk, that query string will look familiar. You can, of course, use all the Splunk functions and so forth to craft your search string, just keep in mind that simpler searches are better. The params argument will be a JavaScript object that contains properties such as earliest_time and output_mode – such as var params={earliest_time:'-4h', latest_time:'now', output_mode:'json'};. I recommend using JSON as the output mode (though there are other modes) because it will be easier to reference when you render the response.
  5. Render the response
    This is where the real magic happens. If you're looking up values – let's say you need to convert a location code like ATL or ORD to an actual longitude and latitude – this would be the place to do it. This is also where you will decide how you're going to format the response – whether it be HTML, JSON, XML, or even plain text. If you're going with HTML, you may want to consider using a templating engine (like dust.js or mustache.js). Using a templating engine means your response can be even more flexible, and using something like Adaro and Makara (see http://krakenjs.com/) gives you even more power.

Of course, using this approach (rather than Simple XML) means you'll have to actually write more of the web page(s), but you'd likely have to do most of the writing in any case. As is noted in the fifth step, if you're using dust.js or another templating engine, it's going to be pretty easy in general – and it will likely be even easier if you're rendering the response as JSON, where your Splunk App Portal is acting as a proxy for the Splunk server. Why might you want to do this? For many of the same reasons you might want to control data coming out of your database – most notably, who gets to see what. Separating functionality in this manner also means the systems are simplified, or at least simpler than combined systems. Since complex systems fail in complex ways, we're avoiding that trap as well.

Overall, even though this is an admittedly simplified explanation, this is a relatively easy process – a process that will likely benefit you in terms of both performance and maintenance once you have established the infrastructure to support it.

Since this is a fairly complex topic and I've not given much detailed information, if you have specific questions about the process or how to do something within this model, feel free to add them in the comments below and I'll address them as soon and as completely as I can.

Happy coding.