Category

Coding

Coding standards: Meaningful Names in Javascript

Intro

This post, is part of a series aimed at creating some basic coding standards for the javascript language.

Even if Javascript is well known for being “flexible”, giving the developers too much freedom when using it, it does not mean that there could not be a standard.

My personal speciality is Javascript, and like many developers, I started to use it adopting my code structure and implementation, depending to the project I was running, the pressure and sometime due to the weather ( I live in Wales, so the weather need to be mentioned!). But recently there have been two main event that have helped me to understand the importance of structure. Firstly  I have started to move toward a Full Stack position, starting to learn new languages and learning different techniques and then I was introduce to Clean Code: A Handbook of Agile Software Craftsmanship, one of the best book on the market for coding standards.

Even if I strongly suggest to read the book as it was very inspiring for me, I am still going to dedicate some of my blog post to analyse and migrate part of the book into the Javascript world, highlighting starting from the use of names.

Note: All the “Bad” examples below, comes from real life experience.

Summary from the book

I have extracted part of the book by quoting the most important sentence of the paragraph accompanied by a real life example. Some section have been omitted as not fully relevant with Javascript.

Use Intention revealing Names

The name of a variable, function, or class, should answer all the big questions. It should tell you WHY it exist, WHAT it does, and HOW it is used.Use Intention-Revealing Names

example 1
 
//Bad
var time;
var diff;
//Good
var todaysTimeInMilliseconds;
var ageDifferenceBetweenUsers;

Use pronounceable names

If you can’t pronounce it, you can’t discuss it without sounding like and idiot.Use pronounceable names

example 2
 
//Bad
var btn;
var usrAdd;
var psw;
//Good
var actionButton;
var userAddress;
var password;

Use searchable Names

If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly name.Use searchable names

example 3
 
//Bad
var dd;
var max;
//Good
var directDebit;
var maxAjaxAttempt;

Avoid Mental Mapping

Readers shouldn’t have to mentally translate your names into other names they already know.Avoid Mental Mapping

example 4
 
//bad
var fn;
var ln;
//good
var firstName;
var lastName

Note: If a loop is bigger than 10 lines, this should have meaningful names too instead than a 1 letter variable.

Don’t be cute

Choose clarity over entertainment value.Don’t be cute

example 5
 
//Bad
var theOnlyButton;
var killSwitch;
//Good
var submitForm;
var closeWindow;

Pick one work per concept

Pick one word for one abstract concept and stick with it.Pick one word

example 6
 
//bad
var fetch;
var retrieve;
var get;
//Good
//use just one across all the project.

Use solution domain name

Remember that people who read your code will be programmers.Use solution domain name

 

example 7
 
//Use technical terms:
var queue
var absolute
var length

Do it for your future self

It is always easy to quote a great artist, or to create a couple of examples, but the hardest part is to actually merge this small little tips in your everyday life.

I have seen an amazing improvement in my code quality and sharability ( ability to share my code with other developers without the need to add comment or explanation). I wanted to start and write this post to make people realise the importance of this small little changes.

Sometime we think that by using a very short variable we have saved ourselves time, but it is completely the opposite. The code that we have just written now, will be read many times, not only by yourself while developing but also down the line when the next update will be required in the future ( prob still you in 6 month time) or by a developer that will have no business knowledge, and that extra second that you have saved in naming a variable with a short name will be lost over and over again overtime.

Spending some extra time on deciding the correct name for a variable is worth every penny, sometime the best thing when in doubt is to ask a colleague, there is no one, better that someone that doesn’t know anything to support you in this hard task.

From practice to real life

I have written the following code to show a real life example and show how a few little variables can really change the speed with which we can read and understand the code. This is not to say that the code is actually perfect, but it is surely an improvement.

The following 11 lines of code, have nothing wrong. It is a normal function with a couple of “For loop”.

Lets read it:

Real Example 1
 
var updateObj = function(obj){
    for(var i = 0; i <= obj.length; i++){
        var sum = 0;
        for(var a = 0; a <= obj[i].marks.length; a++){
            sum += obj[i].marks[a];
        }
        var avg = sum / obj[i].mark.length;
        obj[i].exc = (avg >= 70) ? 'Yes' : 'No';
    }
}

Was it easy to read, does it explain what it does since the start?

Well, this is what most people code will probably look like. I have probably created an extreme case, but many of the pattern in the above code can be found everywhere ( the user of updateObj as variable name, or name a variable sum because is s sum of number).

The same code, with a little clean up on around names will look something like:

real example 2
 
var addExcellenceFieldToStudentsObj = function(obj){
    var students = obj;
    for(var i = 0; i <= students.length; i++){
        var student = students[i];
        var sumOfCurrentYearMarks = 0;
        var numberOfMarks = student.marks.length;
        for(var a = 0; a <= numberOfMarks; a++){
            var mark = student.marks[a];
            sumOfCurrentYearMarks += mark;
        }
        var finalMarkAverage = sumOfCurrentYearMarks / numberOfMarks;
        student.excellence = (avg >= 70) ? 'Yes' : 'No';
    }
}

The function main login is still the same, and the two For Loop are still there, but not there is a different flow when reading the code.

You don’t need to arrive at the end of the function to know that we are working on the studentObject ( the function name is now easily searchable), and you don’t need to reach the tenth line to understand that by sum we mean sum of mark.

Conclusion

This is just a small example of the power of naming. If used properly it can really change the way we develop and the way people see our code. It increase quality, readability and remove the need of comments (that are not needed if a code is well written).

I am astonished by the amount of time I have spent time reading a code over and over to understand what i really does before being able to change it, and even more surprised when that code was written by myself. I have since when making sure every file I create or update will have the same kind of “naming refactoring” showing above, as the effort is minimal ( it doesn’t change logic and if the test is covered by automatic test is quite a log risk change), but the improvement is enormous.

I hope you too share the same feeling and will help me create this standard across the industry to make Javascript a cleaner and more consistent language.

 

From Website to Mobile App

Progressive Web App

Progressive Web App is a collection of web technologies that is aimed at offering a fast, reliable and engaging  experience for application (progressive-web-app), even when the app is accessed offline.

This post is going to cover one of the technologies offered by the progressive app, the “Web App Manifest”.

The manifest is very powerful, because even if  simple to implement and deploy on your website, it will actually enhance the user experience, making your website look like a native application, by making it accessible straight from the home screen without the need to be downloaded from any AppStore.

Unfortunately as every new trend used accross the web, the support of this functionality is still quite low, but recent adoption of this in chrome and Firefox have made this feature worth learning (web-manifest-support).

The manifest file is accessible by anyone from the debugger tool offered by chrome within the Application tab. This tab is also used for other Progressive Web App feature like the service worked.

manifest from debugger
twitter manifest from chrome debugger

How to include a manifest

A manifest, as mentioned above, is just a simple json file that will include basic information about your app. The file can be added in your website like any other resource, by being referenced in the page header within a link tag.

link
 
<link rel="manifest" href="/web-manifest.json">

 

The manifest Details

The manifest does not require all fields to be filled in, in fact in this post, we are going to cover what we believe to be the most common arguments.

The minimum requirement of  a manifest file are name, description and a single icon.

Name and description

The first fields are off course the core of our app, and cannot be anything different that name and description. This give basic details about the app (description), and are used as label for the icon (name).

name
 
"name": "MyApp",
"short_name": "MyApp",
"description": "This is my app and is amazing!"

Icons

The icon section is probably one of the most important and required field for the manifest. It specify the location of all different icons, divided by size and density.

Currently there are 6 different icons sizes in the mobile world and they are 48px, 72px, 96px, 144px, 168px, 192px.

The example below will cover just one icon example, but for best result across devices all of the above should be covered.

icons
 
  "icons": [{
    "src": "images/touch/icon96.png",
    "sizes": "96x96",
    "type": "image/png",
    "density": 2.0
  }]

background_color

This is an interesting field, that when used, will give your app a nice touch.

The background color specified in this field will be applied to the app on click, before the stylesheet is loaded. If used correctly ( so for example if the colours are different from this field and the real background), it will notify when the app is loading.

The color can be specified directly with a supported color name (red) or the or by HEX color code (#333).

background_color
 
 "background_color": "#333"

display

This is the field of excellence, this setting will increase the user experience by giving you the ability to open the app fullscreen removing any browser interface.

The display field can accept four settings (fullscreen, standalone, minimal-ui, browser).

The fullscreen value is what provides the app the native look we have all been waiting for.

display
 
 "display": "standalone"

related_application

If you are reading this post, the filed below will most likely not fit your need. But it was too important to be left out.

The related_application array, will inform the mobile device, that there is a native application with a specific link to the AppStore.

related_applications
 
 "related_applications": [
  {
    "platform": "play",
    "url": "https://play.google.com/store/apps/details?id=com.example.myapp",
    "id": "com.example.myapp"
  }]

When the a related native app is available, and if the app provides additional feature from the Progressive Web app, then the user car be notified that the native app is preferred with the following field. This should be avoided if both the website and the app offer similar features.

prefer_related_applications
 
"prefer_related_applications": true

others

There are many other settings, such as orientation, start_url, service_worker, lang. But I wanted to focus on the most important points and leave you the possibility to go and investigate further what the manifest and the Progressive App technology has to offer.

The manifest is still in draft, but due to its progress in browser support and wide use across the internet, is surely going to make is way to the standards soon.

Reference

Main image from: http://marketingland.com/

W3C manifest proposal: https://w3c.github.io/manifest/

Transactional email made easy – Postmark

Every developer in their career has been asked to build a transactional email at least once. It usually starts with a simple request like:

Please could you send a simple email when a contact form is submitted, something very simple, nothing special.

A few minutes search on Google or Stackoverflow and “snap”, we find perfectly what we need, the php mail function just does what we need right? The description says “Sends an email” what can go wrong?! Well LOTS.

So we have then starter to create our own implementation of a safe mail sender, we start to create templates, we improve our knowledge of crazy workaround needed for HTML formatting in emails and of course they end in the spam, no matter how clear the content is and our previous excitement just turned into our biggest nightmare.

Don’t reinvent the wheel

Unfortunately the reason why I am writing this post, is because I have been there. I have gone through all the nightmares explained above, and trust my words when I say the word nightmares.

There are company that with great product and the right marketing campaigns, have been able to became the leading providers in the industry (eg. WordPress, Mailchimp, etc..).

Today I am going to share with you what I found to be one of the best provider in transactional email that maybe and hopefully be part of that “right marketing campaigns” that can helps them.

Mail sent and delivered.. hassle free!

Over a year ago, I was ask to implement an easy to use way to create Email templates, that would be reliable, easy to change (code free) and with added analytics. (the conversation started with the sentence shared above.. it was supposed to be an easy job they said 🙂 ).

Postmark was my final choice and I have no regret as it has not only delivered all it was required for me, but it also provides fantastic customer service ( fast and reliable) with affordable plans (They provide initial 25000 email free, plus extra free token that are provided as the service get used more, that is more than enough for a small/medium company).

See to believe

I am going to post below a small example taken directly form my project by creating a very simple email template and show the code required to deliver it. There will be no explanation on how to create an account, and how to fetch the unique key, as the documentation of the website is just great on that.

Step 1 – Create the template

Login into your account and then click on the “Add a new template” button situated in the template section.

postmark crreate templace
Postmark create template screenshots

 

Postmark provides you with a list of templates. Each of the templates provides a very details post with all the information required to create your own version of the template with tons of tips around email requirements, but it also give you the ability to use the open source templates provided by them, or of course start from a blank canvas.

For the purpose of this example we are going to use the existing Welcome template.

Step 2 – Modify the template

Postmark template example
Postmark template example

The Web App provides a very easy to use IDE, everything is within reach, and the template provides you with all the basic structure and example needed.

This editor provides you with a Template name, Subject line, HTML editor, live preview, a variables object, ability to fill the email with test data to see how the email layout will react, a “Send Test” button to see what an email really look like and to finish off, an “API snippets” .

 

postmakr api snippets
postmark api snippets

The snippets provide you with everything you need, all the code has been dynamically filled with your account information, the template id and also all the variables.

The code is provided in 5 different languages curl, Ruby, C#, PHP and Node.js.

If this snippets is not enough, you can be assured to be supported by a great customer service ( I had a lovely personal experience and I deals with 3 different people).

 

 

Step 3 – The code

After creating your HTML template and setting the right variables and small details, there is nothing else left than copy this snippets into the portion of your code than handles the email and replace the variable with actual values.

PHP snippets
 
// Create Client
$client = new PostmarkClient("000000000000-0000-00000000000");
// Make a request
$sendResult = $client->sendEmailWithTemplate(
  "sender@example.com",
  "recipient@example.com", 
  1526526,
  [
  "name" => $_POST["name"],
"username" => $_POST["username"]
]);
?>

That is it, no more code required.

Conclusion

I am usually reluctant to use external tools or API as it makes your product fragile, but there are some cases where the risk is worth while, and this is one of them.

The tons of hours I saved after introducing Postmark and clear way to use it has made this a must have for every of my project small or big.

In this post I have really just touched the surface, as the Web App offers many more features and benefits ( for example low possibility of spam because they make sure no one uses the APP for spams emails and they do any effort to keep the servers clears), and hope after trying it out, you will share my same view.

Reference:

Postmark – https://postmarkapp.com/

image from postmarkapp website

"