Guide to the Style Guide

Let first start with what this post is not and that is a style guide for clothing, make up or hair. This is about Coding Style Guides, what they are, if you should have one and if so then what one. I will mainly be following it through with JavaScript, but the knowledge can be transferred to other languages as it is the principle that I am looking at.

What is a style guide?

A Style Guide is a set of rules for your code to follow. These rules start from as simple as putting a semicolon at the end of the lines, and only using single quotes around strings. However the rules can be expanded to describe how you should format your code, for example how to format a function, the file naming convention and how to set up error checking. In short it is a guide of rules and patterns for developers to follow to create a consistent and fluent code.

Style Guides and their practice have been about for many years, but I feel with more languages and standards being put in place they have become more prominent. One of the earliest writing is a book called The Elements of Programming Style, which talks about the coding rules from its time for Fortran and PL/I languages. Though the languages are more out of date, the principles are not and can still be taken into account for todays standards. Most tutorials and beginners guide to languages, will also have some kind of style guide in them, so you can learn from their patterns what to conform to.

These guides don’t have to just be words on a page as well. The guides are able to be built into your Continuous Integration Builds. This would mean when your application builds it can produce errors or warning about your code and how to fix them before you merge into the shared code base.  Better yet,  you can get extensions built into most all the common coding editors that will evaluate your code as you type or on save of the code. Therefore you don’t need to wait until the end point when you are checking in to find out your problems. This can save time and also drill in the practices to your mind, so soon you will be throwing out the styles as you go with no help.

Should you have one?

This is a simple question with a simple answer, yes. Why would you not have one of these in practice at your company or even in your personal workflow. To conform to a style guide is an easy task for anyone to get started as there are so many tools to test your code. However if you have a large code base and then you decide to get a guide in place then it could take sometime, but worth it. Think if you have all types of developers putting their own twist in the code base and then they need to read each other code. It would create a bit of a muddle as they would need to understand the previous developer patterns to understand the code. Worst thing would be, does that developer conform to the previous developer standard or put their own in. This would then create a hybrid that creates more hassle for the next developer.

As you can see the guides can benefit you a lot, but not just for other developers reading your code. When you are creating code you want to make sure it is readable by yourself as well. If you think about, that you might not come back to a peace of code for a long time, with a style guide in place and in practice, you would be able to read the code more easily. It also then gives you a standard of coding, so your not just spitting out some Frankenstein code that just about works, but instead you always have a consistent level of code produced. With consistence code and naming conventions it then also make life easier when your 30,000 lines down the bottom of the page and you need to remember how you call that method. The style guide that pushes you to have a pattern to your naming, will then give you the ability to know how the method will be named. Therefore you won’t need to hunt it down as you will either just know the name or at minimal know how to search for it.

The people it should also be benefitting is the other developers working on the same code and also the company that could be recruiting another developer. If the standard is in place then it doesn’t matter who walks up to your code, they will be able to read it easy and also be able to update the code easier. The other perks of following the guide are the same that will benefit the individual user like simpler to find files names, update code and keep consistency.

Which one?

Well 99% of the time I would say not to build your own, but there is that small 1% I would say yes. This 1% time I would say yes, is for if you are a big enough company to require your own style guide. As the guide is just for coding then there is not customer vision of this, therefore it is not vital that the style guide represents your company image. Saying that though, some companies may prefer to have there own rules to follow as it might fall inline with other style guide or other company procedures. Either way it should only really be done if they must have to.

The reason to still use a popular  open source one is because it is just that, open source. This would mean that when the ECMAScript gets updated or any other language versioned, the community will update the style guide to comply with the latest version. This can take some time if it is your own, to update to a new version and have meetings internally to decide what the update is. However if the open source owner or community do it, then you don’t have to.

This then also back up the point that if another developer is recruited, they may know the open source style guide and be able to pick up the code base easier. If the style guide managed by your company or yourself, then you have no chance of the developer understanding the guide first time.

If you do decide to be in the 99% section, then which guide do you go for? This is where the power of the internet comes in. As I mentioned at the beginning, I am focusing this on JavaScript, but it can be transferred to other languages. Therefore for the JavaScript world I would suggest Airbnb Style Guide, because from what I have read and researched it is the most used guide. Of course this doesn’t make it the right guide, but other than the majority of the developer community can’t be wrong, the guide also looks good. From me using it I can tell it is up to date, well maintained and well supported by other extensions like linters. This for me says it is a good choice to go for and so I would use the same method for looking at other style guides for other languages.

To find other guide I would suggest using a search engine to find a guide for your chosen language, or speaking of search engine, Google has a style guide for a lot of languages and it will of course be up to date. You can find it here on Git Hub.

Some Further Reading…


Visual Studio Code Cookie Snippet

If you didn’t know, Microsoft release an editor called Visual Studio Code and if you didn’t know, Visual Studio Code can handle Snippets and extensions. These Snippets can be created by Visual Studio and by the coding community. These can be simple modules to help coding or full languages. I have found a use to generate a snippet of code that I always use and so I have made this into a Visual Studio Code Snippet. Read on to find out what and how to use it.

What is it?

The Snippet is called CookieJs and by the title you can guess it is about cookies in JavaScript. This snippet produces 3 methods for running cookies. One is to set a cookie, one is to get a cookie and finally a method to check if an cookie exists. These three methods can be produced separately, plus also it can be produced as a JavaScript object.

How do you get it?

If you download Visual Studio Code first of course and you can do the following

  1. Install Visual Studio Code 0.10.1 or higher
  2. Launch Code
  3. From the command palette Ctrl-Shift-P (Windows, Linux) or Cmd-Shift-P (OSX)
  4. Select Install Extension
  5. Type CookieJs
  6. Choose the extension
  7. Reload Visual Studio Code

 

How do you use it?

So like most snippets, it is easy to use. You simply have to type in one of the 4 keywords and they will produce the respective snippets of code.

 

'cookieobj' for full CookieJs object

'chkcookie' for Check Cookie Function

'getcookie' for Get Cookie Function

'setcookie' for Set Cookie Function

 

CookieJs

 

A little snag that kept getting me is to remember to have the language setting set to JavaScript. To change this you need to click the Language Indicator, which is down in the bottom right hand of the status bar. This will bring up the Command Palette for Select Language Mode. You can read more about the languages here on Visual Studio Code site on Languages.

 

Screen Shot 2016-04-27 at 20.18.15

You can get this snippet and more from this link here to my CookieJs. 

 

JQuery Validate for 3 field date

A difficult and challenging task I had been given is to use the JQuery validate.js to validate the date fields, but this was then split out into 3 fields. One for day, month and of course year, which sounds easy, but it was not. The issue comes that validate.js is built to validate one field on its own and we wanted to validate not just each field, but also as a whole date.

I researched the web and most developers suggested amending the JavaScript library file. However the version we had was minified and of course we had other teams using that copy, so using this method would affect others code. I thought about putting the validation for the whole date in with each of the fields, but this then produced the same validation each message for the whole date 3 times because it was doing it for each of the fields. There was a suggestion from developer to use a group method, but I couldn’t seem to get that working.

So I persisted to make my own method. This may not be the best, but I found it worked well and passed testing so it can’t be that bad. You can read more about the library of JQuery Validate here and learn the basics, which will make this all seem a bit easier.

First we need to validate each field on their own for example make sure the month is between 1 and 12. Instead of making a validation made for each field I made a universal method that all of them could use.

In the example below you can see in the ‘params’ parameter I passed in a array that has the minimal number and the maximum number. You would pass for example of month [1,12]. This is then validated on exit to check the ‘value’ of the field, stored in ‘dateValue’, is between or equal to the range.

$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);
var Min = parseInt(params[0], 10);
var Max = parseInt(params[1], 10);
return this.optional(element) || (dateValue >= Min && dateValue <= Max );

},"Please enter a valid age"

);

You can then attach this to the field like so:

//Month validation
$(".month").rules("add", {

vailddatefield: [1,12],
messages: {
vailddatefield:  'Please enter a month value between 1 and 12'
}

});

The issue then comes when you want to validate these all together. If you was to enter the validation for the whole date in the method above then when an error happened it would produce the message once for each field with the same text. This then means we need a single field to evaluate if the full date is valid and then validate against that.

If you add the below snippet into the previous method, you can then pass the class or IDs for each of the date fields. These can then be concatenated together to make a full date, then put into a hidden field. This now holds our full date string in good format ready for validating.

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

This however still doesn’t solve how we are going to validate it. To fire the validation by the library as normal, you need to give focus to the field then leave it, which is impossible because it is hidden. So we use some magic… If you put the below statement in, it forces the JavaScript to validate that field. This then runs its attached validation from the library. If you enter this into the previous method as well, so no matter which fields they start or finish in, it will validate the full date in the end. You will also only get only one message to appear if the field is invalid.

$(fullDate).valid()

Something I also did was stop it validating until all the fields are complete, as you don’t want to say their date is invalid before they even get chance to fill it out, so I changed the above to be the below. This then checks that each field has it minimal length of value before it validates the whole date.

if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid()          

 }

You can now see the whole code for the validation method. This will validate each field on its own, while also validating the whole date. You will need to add your own method for validating the full date, but if you read up on the library this should be easy.

/// Check Valid date
$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);

//Get max and min dates
var Min = parseInt(params[0], 10);
var Max= parseInt(params[1], 10);

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

//enter full date
$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

//Validate full date
if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid();

}

return this.optional(element) || (dateValue >= Min && dateValue <= Max);

},"Please enter a valid age"

);

Below here you can then see the example of calling the new methods for Month and for the full date. You can always also add more validation methods.

//Month required
$(".validate-month").rules("add", {

vailddatefield: [1,12,'.day','.month','.year','.fulldate'],
messages: {

vailddatefield:  'Please enter a month between 1 and 12'

}

});

//full date
$(".validate-date").rules("add", {

vailddate: '',
messages: {

vailddate:  'Please enter valid date'

}

});

Any thoughts and other methods people have seen can be shared in the comments section below.

ARIA Control JavaScript Library

This is a library to automatically inject the standard for screen readers mark-up ARIA. ARIA is Accessible Rich Internet Applications which is a way to make websites and applications more accessible to people with disabilities.

This libraries purpose is to automatically inject the necessary tags and commands to the users mark-up, so that it meets the standards as much as possible. There are also commands for the users to inject the methods on to specific parts if the library does not get them automatically. Also the automatic functionality can be turned off if only partly needed.

Download the library on GitHub 

View the examples on CodePen

Here are some helpful links about ARIA to help understand the tags and their values.

 

ARIA Control Library V1 Method Breakdown

Hidden (has auto)

This detects all the elements that are ‘display:none’ and/or ‘visibility:hidden’. It will then add the ARIA ‘aria-hidden’ and give it a role of ‘presentation’. This makes the element hidden from screen readers. There is also a method to make the element un hidden if the state changes.

Hidden Message (has auto)

This method uses the given class in the options to make the element display off the page. This means that the screen reader can see the message and read it out, but sighted users won’t be able to see the message. This is useful if you want to give extra information only to the users using a screen reader.

Notifications

This sets the attributes for ‘aria-atomic’, ‘role’ and ‘aria-live’. These are the attributes best served as a notification.

Alert (has auto)

This is for error messages and other alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: rude’. This can be automatically run with a set class.

Warning (has auto)

This is for warning messages and other none critical alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: assertive’. This can be automatically run with a set class.

Message (has auto)

This is for any message that is not critical like a success message. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: polite’. This can be automatically run with a set class.

Required (has auto)

Any element, usually inputs, that has the attribute ‘required’ on them will have the ARIA tag ‘aria-required’ added to the element. This can also be done manually by passing the class.

Popup (has auto)

With this method you need to set up the popup classes for the control and the popup. It is mainly aimed at the tooltip example, e.g. if you click in a field and then a tooltip shows. The method will give the control the aria tags to show it has a popup and the tooltip the tags to show what controls it. You can also pass the role type, but by default it is ‘tooltip’.

Show and Hide Popup

These are more helper methods to the above. When the popup shows or hides you can call these method to update the elements settings.

Checked Elements (has auto)

Both Checkboxes and Radio buttons will automatically have the check item injected with the ARIA ‘aria-checked’. This marks if the element is checked or not, for which the change event is also added to all of the elements so if it becomes checked or unchecked then it is updated.

Disabled (has auto)

Any disabled element will have the ‘aria-disabled’ tag added to it.

Selected Option (has auto)

This will make all the options in a select element ‘aria-selected: false’ then find the selected option to set it to true. It also adds the event change to detect when the selected has changed and updates them.

Max and Min (has auto)

This will mainly be for inputs with a max or min value. It finds if they have a value then puts them in their relative tags, either ‘aria-valuemin’ or ‘aria-valuemax’.

Navigation (only has auto)

A complex one, but easy to set up. With all the correct settings this can add the tags to show up to screen readers as a navigation. It will also tag the links as menu items and the sub menu as well as being a popup. It uses the hover event to detect when the sub menu is being shown.

Button (has auto)

This will detect the all button types and add its role as ‘button’

 

ARIA Control Library V1 Options Breakdown

autoDetect (default = true)

This determines if to automatically tag the elements or to only allow manual running.

alertClass (default = .acAlert)

Used for the auto detection for Alert Notifications.

warningClass (default = .acWarning)

Used for the auto detection for Warning Notifications.

msgClass (default = .acMsg)

Used for the auto detection for Message Notifications.

popupClass (default = .acTooltip)

The class of the popup or, as the example was, the tooltip.

popupCtrlClass (default = .acTooltipCtrl)

The element that triggers the popup or tooltip to show.

popupType (default = tooltip)

The role of the popup.

hiddenMsgClass (default = .acHiddenMsg)

The class of any hidden messages that don’t show to slighted users.

navClass (default = .acNav)

The navigation containers class.

navParentClass (default = .acSubNav)

The top level links class.

navSubNavClass (default = .acSubMenu)

The sub menu class.

Galen Framework Hover in JavaScript

A bit of a small audience for this one, but a project I was put on wanted us to use the Galen Framework to test their UI. For people who do not know what this framework is, it is a method of writing acceptance code that matches up to the output in the browser window. This can be coded to work for all different device, sizes and URLs. One hard space I came to was to action the hover state of an element and then test it.

If you would like to read up more about the Galen Framework first then you can find all the information you need on the website.

To test you can either run it in the Galen syntax to run in the Command Prompt or you can also run it using JavaScript. I opted of the Galen Syntax for no real reason, but there was a method to action the hover in the JavaScript version.

Ivan Shubin, the creator of the Galen Framework, point me here for the example.

load("init.js");

load("pages/WelcomePage.js");

 

testOnAllDevices("Welcome page", "/", function (driver, device) {

new WelcomePage(driver).waitForIt();

checkLayout(driver, "specs/welcomePage.gspec", device.tags);

});

 

testOnDevice($galen.devices.desktop, "Menu Highlight", "/", function (driver, device) {

var welcomePage = new WelcomePage(driver).waitForIt();

logged("Checking color for menu item", function () {

checkLayout(driver, "specs/menuHighlight.gspec", ["usual"]);

})

 

logged("Checking color for highlighted menu item", function () {

welcomePage.hoverFirstMenuItem();

checkLayout(driver, "specs/menuHighlight.gspec", ["hovered"]);

});

});

You can see the ‘hoverFirstMenuItem’ that actions the hover. This is built into the Framework that comes with the JavaScript. You can find more about the API and the ‘hover’ method on the Reference Guide for JavaScript.

However I was trying to use the Galen Framework in the command prompt, which can inject JavaScript into the page that runs once the page has loaded. The first idea I had then was to run a ‘hover’ action, which because the site I was running it on has Jquery loaded I could use like below:

$(document).ready(function () {

//hover links

$('a').trigger('mouseenter');

$('a').trigger('mouseover');

$('a').trigger('hover');

$('a').hover();

});

Though as you can see I went a bit overboard trying these all out as none of them seemed to work. I knew the Jquery was working as I was able to run other method to do click events and other thing. After some searching I found a method.

I found a way to get all the style sheets and then search through them. Once I could search them I could find out what the ‘hovered’ styling was for that element. Then I could extract the styling and inject it onto the element, so now its standard style becomes its hovered style.

You can see the below method that I use ‘document.styleSheet’ to loop through each style sheet, then get each rule and loop them. If the class I am looking for is found the I user ‘cssText’ to get all the styling from the rule. This does come back as ‘{background-color:blue}’ so the response text is stripped down to just the CSS.

function getStyle(className) {

            var c = '';

            for (var i = 0; i < document.styleSheets.length; i++) {

try{

                var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;

                if (classes) {

                    for (var x = 0; x < classes.length; x++) {

                        try {

                            if (classes[x].selectorText.indexOf(className) > -1) {

                                var s = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;

                                s = s.substring(s.indexOf("{") + 1);

                                c += s.substring(0, s.indexOf("}"));

                            }

                        } catch (ex) {

                        }

                    }

                }

                        } catch (ex) {

                        }

            }

            return c;

        }

You will notice there is a few try catches in the loops, these are because some style sheets it picks up are not accessible so they create an error in the JavaScript. The try catches mean it can keep looping on through the ones it can access instead of breaking out. Another bug fix is where it uses ‘rules’ or ‘cssRules’ and ‘.cssText’ or ‘.style.cssText’. This is due to different browser standards, some of the browsers use one set and some use the other, this prepares for either case when your tests run.

Below is how the full code sits together and can be used. You can see I invoke the method by passing ‘a:hover’ as it is the hover state I need to access to the link.

$(document).ready(function () {

function getStyle(className) {

            var c = '';

            for (var i = 0; i < document.styleSheets.length; i++) {

try{

                var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;

                if (classes) {

                    for (var x = 0; x < classes.length; x++) {

                        try {

                            if (classes[x].selectorText.indexOf(className) > -1) {

                                var s = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;

                                s = s.substring(s.indexOf("{") + 1);

                                c += s.substring(0, s.indexOf("}"));

                            }

                        } catch (ex) {

                        }

                    }

                }

                        } catch (ex) {

                        }

            }

            return c;

        }

        //all links

        $('a').attr('style', getStyle('a:hover'));

});