Tag Archives: massachusetts

Whatever Steve Jobs Thought, Thermonuclear War Is NOT the Best Way to Get & Keep Talent

It’s nothing personal. It’s just business. Except when it’s not. When Google brought out a smartphone OS in 2008 that let some competition into what had been an Apple-only field, the reception was mixed. Just like with any new tech product, a lot of people were sure they’d never feel the need for one. (I thought the same. Now I have a Samsung the size of a door. I wrote some of this post on it.) Some people were overjoyed – it’s just like an iPhone, except I can afford it. Awesome! And then there was Steve Jobs. Boy, was…

The post Whatever Steve Jobs Thought, Thermonuclear War Is NOT the Best Way to Get & Keep Talent appeared first on The Daily Egg.

Originally from:

Whatever Steve Jobs Thought, Thermonuclear War Is NOT the Best Way to Get & Keep Talent

Thumbnail

Terrible JavaScript Mistakes To Avoid With A Static Code Analyzer

Hardly any line of my code comes out perfect the first time I write it. Well, most of the time… Some of the time… Um, hardly ever. The truth is that I spend more time chasing down my own stupid programming errors than I’d like to admit. That’s why I use static analyzers in every JavaScript file I write.

Static analyzers look at code and find problems before you run it. They do simple checks, like enforcing syntax (for example, tabs instead of spaces), and more holistic checks, like making sure your functions aren’t too complex. Static analyzers also find errors that you can’t find with testing, like instances of == when you meant ===.

In large projects and on big teams, you’ll be happy to have a little help finding those “simple” bugs that turn out to be a lot less simple than they looked.

JSLint, JSHint And Closure Compiler

You have three main choices for static analyzers in the JavaScript world: JSLint1, JSHint2 and Closure Compiler3.

JSLint

JSLint was the first static analyzer for JavaScript. You can run it on the official website4 or use one of the wrappers5 to run it on your local files. JSLint finds a lot of useful errors, but it’s very rigid. Here’s a good example:

var s = 'mystring';
for (var i = 0; i < s.length; i++) 
  console.log(s.charAt(i));

JSLint will show two errors for this code:

Unexpected '++'.
Move 'var' declarations to the top of the function.

The first problem is the declaration of the variable i at the top of the loop. JSLint also doesn’t like the ++ operator at the end of the loop declaration. It wants the code to look like this:

var s = 'mystring';
var i;
for (i = 0; i < s.length; i = i + 1) 
  console.log(s.charAt(i));

I appreciate where JSLint is coming from, but it’s just too strict for me. It was too rigid for Anton Kovalyov6 as well, so he created JSHint.

JSHint

JSHint works similarly to JSLint, but it’s written on top of Node.js7 and it’s much more flexible. JSHint has a long list of options8, making it possible to create custom checks by writing your own reporter9.

You can run JSHint from the website10, but most of the time you would install JSHint as a local command-line tool11 using Node.js. Once JSHint is installed, you can run it against your files with a command like this:

jshint test.js

JSHint also has plugins for popular text editors, so you can run JSHint while you’re coding.

Closure Compiler

Closure Compiler, from Google, is a different breed. As the name suggests, it’s a compiler as well as a checker. It’s written in Java and based on the Rhino12 parser from Mozilla. Closure Compiler has a simple mode to do basic code checking, but it also has more advanced modes to do extra checking and enforce special type declarations.

Closure Compiler reports errors in JavaScript code, but it also creates minimized versions of JavaScript. The compiler removes white space, comments and unused variables and simplifies long statements to make a script as small as possible.

Google makes a simple version of its compiler available on the Web13, but most of the time you’ll want to download Closure Compiler14 and run it locally.

Closure Compiler will output a list of files into a single minimized file after checking their code. You can run it like that after you’ve downloaded the compiler.jar file.

java -jar compiler.jar --js_output_file compress.js --js test1.js --js test2.js

Choosing the Right Checker

In my projects, I combine Closure Compiler with JSHint. Closure Compiler does the minimization and basic checking, while JSHint handles the more complex code analysis. The two work well together, and each covers some areas that the other doesn’t. In addition, I can use the extension capabilities of JSHint to write custom checkers. One common checker I write checks for particular functions that I don’t want, like calling functions that I don’t want to allow in my project.

Now that we’ve looked at a few checkers, let’s look at some bad code. All of these six examples are code you should never write and are spots where code checkers would keep you out of trouble.

This article uses JSHint for most examples, but Closure Compiler would produce similar warnings.

== Versus ===

JavaScript is a dynamically typed15 language. You don’t have to declare types when you’re coding, but they exist at runtime. JavaScript offers two compare operators to handle these dynamic types: == and ===. Let’s look at an example.

var n = 123;
var s = '123';

if (n == s) 
  alert('The variables were equal');


if (n === s) 
  alert('The variables were identical');

The == operator compares the values of the two objects. It converts the objects and compares them separately from their types. The === operator compares the object types and the values. In this case, the first if block will pop up an alert, and the second if block won’t — because n and s have the same value but not the same type.

The == comparator is a relic from the C language roots of JavaScript. Using it is almost always a mistake: Comparing values separate from types is rarely what the developer means to do. In reality, the number “one hundred twenty-three” is different from the string “one two three.” These operators are easy to mistype and even easier to misread.

Check this code with JSHint and you’ll get this:

test.js: line 9, col 12, Expected '===' and instead saw '=='.

Undefined Variables And Late Definitions

Let’s start with some simple code:

function test() 
  var myVar = 'Hello, World';
  console.log(myvar);

See the bug? I make this mistake all the time. Run this code and you’ll get an error:

ReferenceError: myvar is not defined

Let’s make the problem a little more difficult to spot:

function test() 
  myVar = 'Hello, World';
  console.log(myVar);

Run this and you’ll get:

Hello, World

This second example works, but it has some very unexpected side effects. The rules for declaring JavaScript variables and the scopes they end up in are confusing at best.

In the first case, JSHint will tell you this:

test.js: line 3, col 17, 'myvar' is not defined.

In the second case, it will tell you this:

test.js: line 2, col 5, 'myVar' is not defined.
test.js: line 3, col 17, 'myVar' is not defined.

The first case saves you from a runtime bug. You don’t have to test your app — JSHint will find the error for you. The second case is worse because testing won’t find the bug.

The problem with the second case is insidiously subtle and complex. The variable myVar has now escaped from its function scope and been hoisted16 into the global scope for the whole page. This means that it will exist and have a value of Hello, World after the test function has run. This is called “global scope pollution.”

The myVar variable will exist for every other function that runs after the test function. Run the following code after you’ve run the test function:

console.log('myVar: ' + myVar);

You’ll still get Hello, World. The myVar variable will hang around your code like mold, causing tricky bugs you won’t find until 3:00 am the night before you release, all because you forgot to type var.

Variable Reuse

Redefining variables is allowed in JavaScript, but it’s almost always an accident. Take a look:

function incrementCount(counter) 
  if (counter.count) 
    counter.count++;
   else 
    var counter = 1;
    counter.count = counter;
  
}

In this function we’re incrementing the count property on the object that was passed in, but we need to add the property if it doesn’t already exist. See the bug?

This function will never add or increment a counter on anything. The else statement will always be called, and it will redefine the function argument counter. Basically this function creates a new object, assigns a property to it and then loses the object when the function returns. It will never change the object that was passed in.

This simple typo will make the code run without any errors but will produce a very strange result.

JSHint will tell you this:

test.js: line 21, col 21, 'counter' is already defined.

Curly Braces In Blocks, Loops And Conditionals

if (false)
  doSomethingElse();
  doSomething();

Will this code doSomething or doSomethingElse? At first glance, I always think it won’t doSomething or doSomethingElse. That’s the way it works in Python, but not in JavaScript. JavaScript will treat the one line after the if statement merely as part of the block; the indenting doesn’t matter.

This issue is simply about code readability. If you can’t understand what the code will do, then you’ll write bugs.

Python and CoffeeScript like to skip the curly braces. That might work fine in languages that guarantee to format white space well, but JavaScript is looser than that. JavaScript allows a lot of strange syntax, and curly braces will keep you out of trouble.

if (false) 
  doSomethingElse();
  doSomething();

Add the braces and you’ll always make code more readable. Skip them and JSHint will tell you this:

test.js: line 27, col 5, Expected '' and instead saw 'doSomething'.

Single And Double Quotes

console.log("This is a string. It's OK.");
console.log('This string is OK too.');
console.log("This string " + 'is legal, but' + "really not OK.");

JavaScript allows you to define a string with single or double quotes. It’s nice to have the flexibility, like when you’re defining HTML, but the added flexibility can lead to some very inconsistent code.

Google has a code style guide that always uses single quotes for strings, so that they don’t have to escape double quotes in HTML. I can’t argue that single quotes are better than double quotes, but I can argue for consistency. Keeping everything consistent makes code more readable.

JSHint will warn you about mixed quotes like this:

test.js: line 31, col 27, Mixed double and single quotes.

Copying and pasting or mistyping a quote is easy. Once you have one bad quote, others will follow, especially if a lot of people are editing the file. Static analyzers will help keep the quotes consistent and prevent a big cleanup in the future.

Cyclomatic Complexity

Cyclomatic complexity17 is the measure of how complex a given block of code is. Look at the code and count the number of paths that could possibly run: That number is its cyclomatic complexity.

For example, this code has a cyclomatic complexity of 1:

function main() 
  return 'Hello, World!';

You can follow only one path through this code.

Let’s add a little conditional logic:

function main() 
  if (true) 
    return 'Hello, World!';
   else 
    return 'Hello, unWorld!';
  
}

The cyclomatic complexity has jumped to 2.

Ideal code is easy to read and understand. The higher the cyclomatic complexity, the more difficult the code will be to understand. Everyone agrees that high cyclomatic complexity is bad, but no one agrees on a limit; 5 is fine, and 100 is too high — but there’s a lot of gray area in the middle.

If the cyclomatic complexity gets to the predefined limit, then JSHint will let you know.

test.js: line 35, col 24, This function's cyclomatic complexity is too high. (17)

JSHint is the only one of the three checkers that looks at cyclomatic complexity. It also allows you to set the limit. Go above the maxcomplexity number that you’ve set and JSHint will warn you. I like to set the limit to 14, but I’ll go a little higher in projects in which I do a lot of parsing or when I have other reasons to need many code paths.

The real reason the complexity number is important is that it tells you when to refactor your code. The first time you write a long function, it always makes sense. But if you wait six months and then come back to fix bugs, you’ll be glad that you took the time to make it easier to read.

Cyclomatic complexity usually breaks down with laundry lists. For example, I created a calendar, and I wanted to get the correct first day of the week for each country. I had a function that looked something like this:

function getFirstDay(country) 
  if (country === 'USA') 
    return 'Sunday';
   else if (country === 'France') 
    return 'Monday';
   else if…
}

I supported a lot of countries, so the cyclomatic complexity quickly grew to over 50. Although the code was very easy to read, the number of paths was high, so my code analyzer complained. In the end, I split up the function to get the complexity below my maximum. It was a hack for this particular case, but it’s a small price to pay for cleaner code overall.

Check Everything That You’ll Ever Edit More Than Once

Static checkers find the bugs that you wouldn’t come across with simple testing. They also find bugs at compile time, as opposed to runtime — those middle-of-the-night bugs that only creep in when a dozen people are all trying to do the same thing. Finding all of those subtle bugs is a long and painful process without code checking.

I began this article by claiming that I always use a code analyzer, but I don’t in one case: with throwaway code. I like using quick prototypes to show interactive ideas and to help my team come together on how something should work. Those prototypes are write-once code; I never need to fix bugs in them because I’ll be throwing away the prototypes a few weeks later. This throwaway code exists solely for the quick demos, and I don’t care if it has subtle bugs. Everything I care about, though, gets analyzed.

Fixing these types of bugs at the beginning of a project is easy; finding them on the night before you release will drive you nuts. Code analyzers have saved my butt many times, and they’ll also save yours.

Image on front page created by Ruiwen Chua18.

(al, ml, da)

Footnotes

  1. 1 http://www.jslint.com/
  2. 2 http://www.jshint.com/
  3. 3 https://developers.google.com/closure/compiler/
  4. 4 http://www.jslint.com/
  5. 5 https://code.google.com/p/jslint4java/
  6. 6 http://anton.kovalyov.net/
  7. 7 http://nodejs.org/
  8. 8 http://www.jshint.com/docs/options/
  9. 9 http://www.jshint.com/docs/reporters/
  10. 10 http://jshint.com/
  11. 11 http://jshint.com/install/
  12. 12 https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino
  13. 13 http://closure-compiler.appspot.com/home
  14. 14 https://developers.google.com/closure/compiler/
  15. 15 http://www.smashingmagazine.com/2013/04/18/introduction-to-programming-type-systems/
  16. 16 http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
  17. 17 http://en.wikipedia.org/wiki/Cyclomatic_complexity
  18. 18 http://www.flickr.com/photos/7162499@N02/3260095534/

The post Terrible JavaScript Mistakes To Avoid With A Static Code Analyzer appeared first on Smashing Magazine.

See the article here:  

Terrible JavaScript Mistakes To Avoid With A Static Code Analyzer

Thumbnail

Making Modal Windows Better For Everyone

To you, modal windows1 might be a blessing of additional screen real estate, providing a way to deliver contextual information, notifications and other actions relevant to the current screen. On the other hand, modals might feel like a hack that you’ve been forced to commit in order to cram extra content on the screen. These are the extreme ends of the spectrum, and users are caught in the middle. Depending on how a user browses the Internet, modal windows can be downright confusing.

Modals quickly shift visual focus from one part of a website or application to another area of (hopefully related) content. The action is usually not jarring if initiated by the user, but it can be annoying and disorienting if it occurs automatically, as happens with the modal window’s evil cousins, the “nag screen” and the “interstitial.”

However, modals are merely a mild annoyance in the end, right? The user just has to click the “close” button, quickly skim some content or fill out a form to dismiss it.

Well, imagine that you had to navigate the web with a keyboard. Suppose that a modal window appeared on the screen, and you had very little context to know what it is and why it’s obscuring the content you’re trying to browse. Now you’re wondering, “How do I interact with this?” or “How do I get rid of it?” because your keyboard’s focus hasn’t automatically moved to the modal window.

This scenario is more common than it should be. And it’s fairly easy to solve, as long as we make our content accessible to all through sound usability practices.

For an example, I’ve set up a demo of an inaccessible modal window2 that appears on page load and that isn’t entirely semantic. First, interact with it using your mouse to see that it actually works. Then, try interacting with it using only your keyboard.

Better Semantics Lead To Better Usability And Accessibility

Usability and accessibility are lacking in many modal windows. Whether they’re used to provide additional actions or inputs for interaction with the page, to include more information about a particular section of content, or to provide notifications that can be easily dismissed, modals need to be easy for everyone to use.

To achieve this goal, first we must focus on the semantics of the modal’s markup. This might seem like a no-brainer, but the step is not always followed.

Suppose that a popular gaming website has a full-page modal overlay and has implemented a “close” button with the code below:

<div id="modal_overlay">
  <div id="modal_close" onClick="modalClose()">
    X
  </div>
  …
</div>

This div element has no semantic meaning behind it. Sighted visitors will know that this is a “close” button because it looks like one. It has a hover state, so there is some visual indication that it can be interacted with.

But this element has no inherit semantic meaning to people who use a keyboard or screen reader.

There’s no default way to enable users to tab to a div without adding a tabindex attribute to it. However, we would also need to add a :focus state to visually indicate that it is the active element. That still doesn’t give screen readers enough information for users to discern the element’s meaning. An “X” is the only label here. While we can assume that people who use screen readers would know that the letter “X” means “close,” if it was a multiplication sign (using the HTML entity &times;) or a cross mark (&#x274c;), then some screen readers wouldn’t read it at all. We need a better fallback.

We can circumvent all of these issues simply by writing the correct, semantic markup for a button and by adding an ARIA label for screen readers:

<div id="modal_overlay">
  <button type="button" class="btn-close" id="modal_close" aria-label="close">
    X
  </button>
</div>

By changing the div to a button, we’ve significantly improved the semantics of our “close” button. We’ve addressed the common expectation that the button can be tabbed to with a keyboard and appear focused, and we’ve provided context by adding the ARIA label for screen readers.

That’s just one example of how to make the markup of our modals more semantic, but we can do a lot more to create a useful and accessible experience.

Making Modals More Usable And Accessible

Semantic markup goes a long way to building a fully usable and accessible modal window, but still more CSS and JavaScript can take the experience to the next level.

Including Focus States

Provide a focus state! This obviously isn’t exclusive to modal windows; many elements lack a proper focus state in some form or another beyond the browser’s basic default one (which may or may not have been cleared by your CSS reset). At the very least, pair the focus state with the hover state you’ve already designed:

.btn:hover, .btn:focus 
  background: #f00;

However, because focusing and hovering are different types of interaction, giving the focus state its own style makes sense.

.btn:hover 
  background: #f00;


:focus 
  box-shadow: 0 0 3px rgba(0,0,0,.75);

Really, any item that can be focused should have a focus state. Keep that in mind if you’re extending the browser’s default dotted outline.

Saving Last Active Element

When a modal window loads, the element that the user last interacted with should be saved. That way, when the modal window closes and the user returns to where they were, the focus on that element will have been maintained. Think of it like a bookmark. Without it, when the user closes the modal, they would be sent back to the beginning of the document, left to find their place. Add the following to your modal’s opening and closing functions to save and reenable the user’s focus.

var lastFocus;

function modalShow () 
  lastFocus = document.activeElement;


function modalClose () 
  lastFocus.focus(); // place focus on the saved element

Shifting Focus

When the modal loads, focus should shift from the last active element either to the modal window itself or to the first interactive element in the modal, such as an input element. This will make the modal more usable because sighted visitors won’t have to reach for their mouse to click on the first element, and keyboard users won’t have to tab through a bunch of DOM elements to get there.

var modal = document.getElementById('your-modal-id-here');

function modalShow () 
   modal.setAttribute('tabindex', '0');
   modal.focus();

Going Full Screen

If your modal takes over the full screen, then obscure the contents of the main document for both sighted users and screen reader users. Without this happening, a keyboard user could easily tab their way outside of the modal without realizing it, which could lead to them interacting with the main document before completing whatever the modal window is asking them to do.

Use the following JavaScript to confine the user’s focus to the modal window until it is dismissed:

function focusRestrict ( event ) 
  document.addEventListener('focus', function( event ) 
    if ( modalOpen && !modal.contains( event.target ) ) 
      event.stopPropagation();
      modal.focus();
    
  }, true);
}

While we want to prevent users from tabbing through the rest of the document while a modal is open, we don’t want to prevent them from accessing the browser’s chrome (after all, sighted users wouldn’t expect to be stuck in the browser’s tab while a modal window is open). The JavaScript above prevents tabbing to the document’s content outside of the modal window, instead bringing the user to the top of the modal.

If we also put the modal at the top of the DOM tree, as the first child of body, then hitting Shift + Tab would take the user out of the modal and into the browser’s chrome. If you’re not able to change the modal’s location in the DOM tree, then use the following JavaScript instead:

var m = document.getElementById('modal_window'),
    p = document.getElementById('page');

// Remember that <div id="page"> surrounds the whole document,
// so aria-hidden="true" can be applied to it when the modal opens.

function swap () 
  p.parentNode.insertBefore(m, p);


swap();

If you can’t move the modal in the DOM tree or reposition it with JavaScript, you still have other options for confining focus to the modal. You could keep track of the first and last focusable elements in the modal window. When the user reaches the last one and hits Tab, you could shift focus back to the top of the modal. (And you would do the opposite for Shift + Tab.)

A second option would be to create a list of all focusable nodes in the modal window and, upon the modal firing, allow for tabbing only through those nodes.

A third option would be to find all focusable nodes outside of the modal and set tabindex="-1" on them.

The problem with these first and second options is that they render the browser’s chrome inaccessible. If you must take this route, then adding a well-marked “close” button to the modal and supporting the Escape key are critical; without them, you will effectively trap keyboard users on the website.

The third option allows for tabbing within the modal and the browser’s chrome, but it comes with the performance cost of listing all focusable elements on the page and negating their ability to be focused. The cost might not be much on a small page, but on a page with many links and form elements, it can become quite a chore. Not to mention, when the modal closes, you would need to return all elements to their previous state.

Clearly, we have a lot to consider to enable users to effectively tab within a modal.

Dismissing

Finally, modals should be easy to dismiss. Standard alert() modal dialogs can be closed by hitting the Escape key, so following suit with our modal would be expected — and a convenience. If your modal has multiple focusable elements, allowing the user to just hit Escape is much better than forcing them to tab through content to get to the “close” button.

function modalClose ( e ) 
  if ( !e.keyCode 
}

document.addEventListener('keydown', modalClose);

Moreover, closing a full-screen modal when the overlay is clicked is conventional. The exception is if you don’t want to close the modal until the user has performed an action.

Use the following JavaScript to close the modal when the user clicks on the overlay:

mOverlay.addEventListener('click', function( e )
  if (e.target == modal.parentNode)
    modalClose( e );
  }
}, false);

Additional Accessibility Steps

Beyond the usability steps covered above, ARIA roles, states and properties3 will add yet more hooks for assistive technologies. For some of these, nothing more is required than adding the corresponding attribute to your markup; for others, additional JavaScript is required to control an element’s state.

aria-hidden

Use the aria-hidden attribute. By toggling the value true and false, the element and any of its children will be either hidden or visible to screen readers. However, as with all ARIA attributes, it carries no default style and, thus, will not be hidden from sighted users. To hide it, add the following CSS:

.modal-window[aria-hidden=”true”] 
  display: none;

Notice that the selector is pretty specific here. The reason is that we might not want all elements with aria-hidden="true" to be hidden (as with our earlier example of the “X” for the “close” button).

role=”dialog”

Add role="dialog" to the element that contains the modal’s content. This tells assistive technologies that the content requires the user’s response or confirmation. Again, couple this with the JavaScript that shifts focus from the last active element in the document to the modal or to the first focusable element in the modal.

However, if the modal is more of an error or alert message that requires the user to input something before proceeding, then use role="alertdialog" instead. Again, set the focus on it automatically with JavaScript, and confine focus to the modal until action is taken.

aria-label

Use the aria-label or aria-labelledby attribute along with role="dialog". If your modal window has a heading, you can use the aria-labelledby attribute to point to it by referencing the heading’s ID. If your modal doesn’t have a heading for some reason, then you can at least use the aria-label to provide a concise label about the element that screen readers can parse.

What About HTML5’s Dialog Element?

Chrome 37 beta and Firefox Nightly 34.0a1 support the dialog element, which provides extra semantic and accessibility information for modal windows. Once this native dialog element is established, we won’t need to apply role="dialog" to non-dialog elements. For now, even if you’re using a polyfill for the dialog element, also use role="dialog" so that screen readers know how to handle the element.

The exciting thing about this element is not only that it serves the semantic function of a dialog, but that it come with its own methods, which will replace the JavaScript and CSS that we currently need to write.

For instance, to display or dismiss a dialog, we’d write this base of JavaScript:

var modal = document.getElementById('myModal'),
  openModal = document.getElementById('btnOpen'),
  closeModal = document.getElementById('btnClose');

// to show our modal
openModal.addEventListener( 'click', function( e ) 
  modal.show();
  // or
  modal.showModal();
);

// to close our modal
closeModal.addEventListener( 'click', function( e ) 
  modal.close();
);

The show() method launches the dialog, while still allowing users to interact with other elements on the page. The showModal() method launches the dialog and prevents users from interacting with anything but the modal while it’s open.

The dialog element also has the open property, set to true or false, which replaces aria-hidden. And it has its own ::backdrop pseudo-element, which enables us to style the modal when it is opened with the showModal() method.

There’s more to learn about the dialog element than what’s mentioned here. It might not be ready for prime time, but once it is, this semantic element will go a long way to helping us develop usable, accessible experiences.

Where To Go From Here?

Whether you use a jQuery plugin or a homegrown solution, step back and evaluate your modal’s overall usability and accessibility. As minor as modals are to the web overall, they are common enough that if we all tried to make them friendlier and more accessible, we’d make the web a better place.

I’ve prepared a demo of a modal window4 that implements all of the accessibility features covered in this article.

(hp, il, al, ml)

Footnotes

  1. 1 http://www.smashingmagazine.com/2009/05/27/modal-windows-in-modern-web-design/
  2. 2 http://www.smashingmagazine.com/wp-content/uploads/2014/inaccessible.html
  3. 3 http://www.w3.org/TR/wai-aria/
  4. 4 http://www.smashingmagazine.com/wp-content/uploads/2014/accessible.html

The post Making Modal Windows Better For Everyone appeared first on Smashing Magazine.

Read this article:  

Making Modal Windows Better For Everyone