Tuesday 8 December 2015

Code Standards and Conventions for JavaScript Programmers

Code Standards and Conventions for JavaScript Programmers

Although, coding standards and general conventions are important, but in tools like JavaScript, where concept of code validation and or compilation is very weak, these things become very important. Generally, conventions like naming conventions, commenting and code indention may not give any benefit in performance (these will make your code easy to understand and easy to maintain), but coding standards can make a lot of difference.
I may recommend to review my previous article Tips for JavaScript Programmers, from there you can find few important good practices to standardize JavaScript code.  

Important Points

  • JavaScript is case sensitive.
  • Avoid special character in names. Dollar sign and underscore are exceptional cases where required.
  • Generally use camel case.
  • It is better to use complete descriptive name instead of abbreviations, except industry well know abbreviations and acronyms. Index variable like in for are also be an exception.
  • Use proper indention for coding, we generally use 4 character indention.
  • If possible the try to make your function limited to visibility of your screen. So in general 25 lines are more than enough.
  • Always consider minification and bundling.
  • We may try to avoid data type dependent naming.
  • We may try to use name similar to data provider. It is a debatable point as using names similar to data provide may cause security risk, but it will give you ease to maintain code.
  • Always address JavaScript Injection or Cross Site Scripting XSS.
  • Use proper spacing between operators and operands.

File Name

If your application is going to be hosted on Linux environment then keep in mind file names are also case sensitive there. But it is not similar for Windows, in windows file and director names are not case sensitive. It is better to end JavaScript file to have .js extension.

Local Variable

We may prefer following rules for local variables:
  • Use singular name in camel case for local variable of primitive type.
    var topicLength = 10000;
  • Use plural name in camel case for local variable of array and other collections.
    var coloNames = [“Red”, “Green”, “Blue”];

Global Variable

We may prefer following rules for global variables:
  • Use singular name in pascal case for local variable of primitive type.
    var TopicLength = 10000;
  • Use plural name in pascal case for local variable of array and other collections.
    var ColoNames = [“Red”, “Green”, “Blue”];

Private Variable

We may prefer following rules for private variables:
  • Use singular name in camel case starting with underscore for private variable of primitive type.
    var _topicLength = 10000;
  • Use plural name in camel case starting with underscore for private variable of array and other collections.
    var _coloNames = [“Red”, “Green”, “Blue”];

Public Function Name

For public functions, we may prefer to use camel case:
function sayHello(person){
    return ‘Hello ’ + person;

Private Function Name

For private functions, we may prefer to use camel case starting with underscore:
function _sayHello(person){
    return ‘Hello ’ + person;

Class Name

For classes, we may prefer to use constructor to create and initialize object (by the way, there is a good audience, whom are against new in JavaScript). We may prefer to us pascal case for class constructor name, but its variable may use camel case:
function Car(carName, carModle, carColor){
    this.name = carName;
    this.modle = carName;
    this.color = carName;  
    function carData(){
        return this.name + ‘ ‘ + this.modle + ‘ ‘+ this.color;
var myCar = new Car(‘Hona’, ‘City’, ‘Blue’);
alert(myCar. carData ());

Module Name

For modules, we may prefer to use pascal case:
var Config = (function(){
   var baePath = ‘’;

   var _getPath = function(){
      return _basePath;

    var _setPath = function(basePath){
      _basePath = basePath;
        getPath: _getPath,
        setPath: _setPath

if Statement

It is better to avoid single line if. I always recommend to use parenthesis with if and else part even there is single statement.
    //do your action

Loop Statement

It is better to avoid single line loop. I always recommend to use parenthesis with for even there is single statement.
for(var i=0; i<=10; i++){
    //do your action

Single Quotation or Double Quotation for String Values

There is no difference either you use single quotation or double quotations to represent a string. Even you can use both in a program, but it is recommended to use only one of them in a project. I personally recommend to use single quotation.  

JavaScript Code Placement

Please consider following recommendations for JavaScript placement in project:
  • It is always recommended to avoid inline JavaScript coding. Please consider placing JavaScript code in separate file/s. For file naming we may use camel case: viewName.js, controllerName.js, libraryName.js and etc.
  • It is better to place script reference and or code at bottom of HTML.
  • It is must to address JavaScript file caching at browser side.

return Statement

Make sure return statement and expression are on same line and end with semicolon.


For comments we may consider following:
  • Always comment your code, particularly functions and complex scenarios.
  • It is better to use single line comments using // instead of block comment syntax using /* … */.
  • It is better to comment before code.
  • It is better to end comment with full stop.

Monday 7 December 2015

Tips for JavaScript Programmers

Today, I am going to elaborate few tips for JavaScript programmers. These may help you to code of better quality, easy to maintain with better performance. I would recommend to review my earlier post Misconception about JavaScript to get better results.

Always End a Statement with Semicolon

In JavaScript it is not required to close a statement with semicolon (;), a new line will also serve the purpose. But it is highly recommended to close each statement with semicolon. This becomes particularly critical when you go minification. It not only make your code clean, it is also considered to perform relatively better.

Single Quotation or Double Quotation for String Values

There is no difference either you use single quotation or double quotations to represent a string. Even you can use both in a program, but it is recommended to use only one of them in a project. I personally recommend to use single quotation.   

Explicit Variable Declaration

It is highly recommended to always declare variable with var instead of using implicit variable declaration. Keep in mind if you use some variable name, JavaScript considers it as global variable.

Use strict Mode

It is highly recommended to us strict mode. It can be invoked by using following statement in code: "use strict"; It make JavaScript code Secure, Clear and reliable. It is not guaranteed, but with strict mode code is considered to perform better.

Validation of JavaScript

Now many IDEs provide JavaScript validation, even you can use tools/sites like JSLint with manual efforts.

Avoid Expensive Task in Main Thread

JavaScript is basically single threaded. So try to avoid task like long loops in main thread instead try to use Web Worker. Web Worker are executed by browser as background task.

False Result

If you check any of following in condition, they will return false: null, false, 0 undefined, NaN, and empty string. It is interesting that Infinity will return true.

Operator Precedence

Like most of languages JavaScript has following operator precedence for main operators:
  • Grouping ()
  • Not !
  • Arithmetic Operators
  • Comparison Operators
  • AND && Operator
  • OR || Operators

Short Circuit Operators

In JavaScript has &&  and || operators are short circuit.

Immediately Invoked Function Expressions (IIFE)

Immediately Invoked Function Expressions (IIFE) are executed right after loading automatically.
(function sayHello() {

Working with JSON

JavaScript Custom Objects are not JSON. JSON cannot have functions, JSON is a data interchange format and JavaScript supports JSON, but old browsers may have old JavaScript Engine which may not support it. To JSON object from string use JSON.parse and to convert JSON object to String we can use JSON.stringify. Consider using JSON to handle complex data.

Constructor for Custom Objects

It is recommended to use Constructor to initialize and create objects instead of creating object by directly assigning value to properties dynamically. It will not only make your code clean, easy to maintain and faster. Changing schema of an object is relatively slow.

Adding Extension Methods to JavaScript Core

We can add new features in existing JavaScript Core like following example, but it is not recommended to change core library.
String.prototype.lengthSquare = function()
      return this. Length * this.length;

Strict Equality Operator === is preferred over Equality Operator ==

It is prefer to use === over == until unless we don’t have to compare data of different types. Furthermore, in general === is considered to have better performance.


In JavaScript Array is a datatype. When playing with arrays please consider following:
  • Use split instead of delete to remove an element from array.
  • Use push to add new element at end of array, by the way myArray[myArray.length]=somevalue; will do same.
  • Use unshift to insert new element at start of array.
  • On arrays use simple index based loop instead of loop iterator. Simple loop may give better performance.

Default Parameter Value

JavaScript does not provide any feature to specify default value for parameter, but it allows to skip parameter. So we can check and assign default value manually. A good hack is to use conditional or operator, if parameter has been provide to function then its value will be used otherwise provide value will be assigned to parameter as default value.
function myFunction(parameter){
    parameter = parameter || 0;

Module Pattern

Module Pattern is a very good option if you want to control access to functions and data elements. Furthermore, Modules are very helpful if you want to create some common custom repository or common library in your project.

DOM Access

DOM manipulation in JavaScript is always slow. This case cannot be avoided but can be optimized by considering following:
  • Cache references, e.g. save a reference to call in variable and then use this variable again and again instead of calling method to get reference again.
  • When playing with control addition dynamically, it is better to initialize all required properties of a control before adding to DOM.
  • For existing objects, make display:none before changes, and then restore old value of display.

Minification and Bundling

It is always recommended to go for mininfication and bundling of resources like JavaScript and CSS. It not only decrease load time, but it also reduces network cost. Don’t forget to adobe minification safe syntax and practices even you are not planning for Minification and Bundling.

Commenting and Beautification

For production, it is recommended to not to have extra spacing and comments in JavaScript. It costs extra resources including bandwidth, processing. But for maintenance, it will be preferred to: comment code particularly complex code, indent code, create regions, proper indention. If you are going for miification then these will be removed from minfied version.

JavaScript Code Placement

Please consider following recommendations for JavaScript placement in project:
  • It is always recommended to avoid inline JavaScript coding. Please consider placing JavaScript code in separate file/s.
  • It is better to place script reference and or code at bottom of HTML.
  • It is must to address JavaScript file caching at browser side.

Important Readings

If someone is interested to mastering a tool then it is always required to explore a tool thoroughly. I may recommend to review following topics again (every item is a complete topic):
  • Error Handling
  • Regular Expressions
  • Object Oriented Programming
  • Module Pattern
  • DOM
  • Browser API
  • Local Storage
  • Offline Browsing
  • Event
  • Form and Client Side Validation
  • AJAX (Asynchronous JavaScript And Xml)
  • Animation, Graphics, SVG, Canvas
  • Cookies
  • Web Workers
  • JavaScript Libraries
  • Debugging
  • JavaScript Code Validation/Error Checking

Miscellaneous Tips

  • It is always good to device some naming conventions. We will have a detailed manuscript on this topic in future article.
  • Proper code indention and region where possible.
  • We may use switch instead if cascade if wherever possible, because it is cleaner and faster.
  • String concatenation is an expensive action.       
  • Be specific to use eval(). Use this feature as last option as it is slow and have security issues.
  • Avoid with statement, its usage is generally discouraged. It is forbidden in strict mode.
  • Declare variable outside the loop.
  • It is better to use Custom objects instead of defining too many global variables.
  • If you are interested to code high performance application then try to avoid dynamically typing. In simple, use same type of variables in an expression.
  • Never forget to address JavaScript cache management to handle script changes in web applications.
  • I may highly recommend, to get prepared for ECMAScript 6. If possible then try to code close to this standard, this habit may help you a lot in future to migrate your existing code very easily. 

Saturday 5 December 2015

Misconception about JavaScript

There are lot of misconceptions about JavaScript. Let us discuss few of them. 

JavaScript is not Java

It is very much necessary to clear that JavaScript has no relation with Java. It was initially named as LiveScript. It has been compliance with ECMAScript 5 Language Specifications. Just keep in mind, both Java and JavaScript are different animals.

JavaScript is not Just a Web Development or Client Side Tool

JavaScript is a complete programming language and it is not only used in as front end technology, it has emerged as strong candidate for future in Server Side Development i.e. Node.js.  

JavaScript is not Typeless

JavaScript is not typless, like most scripting languages, it associates type with values, not with variables. It is described as Dynamic Typing. It has six primitive data types: Boolean, Number, String, Null, Undefined and Object

JavaScript is Object Oriented Language

Most of use thing JavaScript is a structural language, but in actual it is an Object Oriented Language. Everything in JavaScript is an object and it supports both of inheritance and aggregation. It is described as Prototype Based Object Oriented Programming Language.

Browser API is not part of JavaScript

Things like Window Object, Location Object, DOM are not part of JavaScript itself, these are browser features and JavaScript just provides API to use them. These API in general called as Browser API, and they can vary from browser to browser. And this dependency is main reason to have problems to program for cross browser site development.

Block Scope

Unfortunately, JavaScript does not respect block scope for undefined variables (variables without var, they are treated as global variables). So be careful with implicit variable declaration. Furthermore, in JavaScript block scope is at function level not set of curly brackets.

JavaScript is not Context Free

In general, we consider it does not matter either a line is ended with semicolon or not, but it can cause many issues particularly in case of minification.

Validation of JavaScript

Now many IDEs provide JavaScript validation, even you can use tools/sites like JSLint with manual efforts. It’s not bad idea to use JavaScript strict mode.


JavaScript is basically single threaded.

this Keyword

this keyword may refer to different things with respect to context. For example, in constructor this refers to object, in simple function this refers to window .

JavaScript Custom Objects are not JSON

JavaScript Custom Objects are not JSON. JSON cannot have functions, JSON is a data interchange format.


A closure is a function having access to the parent scope, even after the parent function has closed. Closures are very interesting feature and very similar to delegates with persisted state of outer function.


It is little tricky yet very simple to debug JavaScript code. We may discuss this topic in detail in future articles.

Context and Scope are Different things

Context and Scope are different things, in simple we can say Scope defines accessibility and life span, on other hand Context refers to what and where.

JavaScript Libraries and Frameworks

There are lot of hot topics like Jquery/ Jquery UI/ Jquery Mobile, AngularJS/Ember, Knockout JS, Kendo UI, Node JS, Lo Dash, React JS, Chart JS, Ionic and etc. these all are libraries and or frameworks developed in JavaScript. These are add-ons not the competitors.

Thursday 3 December 2015

Tips and Rules for Email

We are technical folks. We always like to talk about tools and technologies and of course, it should be focused mainly. But with this attitude we generally ignore few important things including communication skills.  I am going leave topic for open debate if it is Technical or Non-Technical topic. A good alternate title can be "Email Ethics".

Always Respond, Never React

 "You may not be able to control the events that occur during the day, especially those events that are unexpected and challenging. But, you definitely have a choice whether you are going to allow these events to ruin your day, and how you are going to face these challenges."
Barry Gottlieb
Don't send e-mail when you're tired or furious. E-mail can easily be angry, hurtful, or critical. It takes a lot of time to undo the damage.

Delete Unnecessary Email

You have several choices, Scan headers, and delete/archive everything you don't need to know or act upon materially. It's okay to ignore an e-mail the same way you might a letter or a phone message.


When replying to an email be sure to make sure if you want to send the attachment already with the email. Otherwise KINDLY use the reply button instead of forward. Also when sending an attachment, make sure the reader is able to open the attachment - use the lowest common denominator for sending files. Mention Attachments with brief description and use logical name for attachments.

Targeted and Relevant Audience Only

 Treat email like letters and phone calls; wait for a calmer moment to respond. Remove irrelevant people from To/CC/BCC. Rule of thumb; think once before “Reply All”.

Email Subject

Be specific with Subject. Ideally subject must be relevant to email. A good idea is to begin subject with the project name, followed by context. Many among us are working on multiple projects.

Email Signature

Keep proper email signatures. It is recommended for everyone to keep the same signature format with/without logo within a company. And if possible then consider including name of your backup resource.

A Stitch in Time

Take advantage of the timesaving bells and whistles your e-mail program offers. Be responsive to your emails and try to respond within reasonable timeframe.

Avoid Time Wastage

There is considerable time being wasted which must be conserved so that it can be put to other important things. Email is for communicating, but communicating effectively and clearly.

Address Book

Keep an up-to-date address book, and never delete names and addresses. You never know when someone will come back into your digital life.

Break the chain

Chain email is not only tacky, it's banned on many corporate networks. Try and keep the chains small. For example, if this is the fifth revision of FS then please state so in the Subject line.

Email is not for Chatting

Email is not a communication medium for rapid interactive communication, if you need rapid interactive discussion then it is better to consider some other alternatives like phone call or IM tool.

General Rules

In general it is always good to consider following, believe me, these may help you directly or indirectly.
·         Always perform spelling and grammar checking. Few email clients provide the facility to perform spelling checking before sending email.
·         Avoid shortcuts, emoticons and slangs.
·         If you are on leaves or out for long meeting then consider features like auto responder.  

Tuesday 10 November 2015

Tips for Dot Net Programmers

Today I am going to share some tips for Dot Net programmers and using C# as main reference language, hope these tips can be helpful to get performance and maintain code standards:
  • Always try to use “using block” with critical and expensive resource like connection, stream and etc. If it is not possible to use using block then explicitly call close/similar method.
  • If any generics is not useful or local instances of generics is going out of scope then explicitly call clear for that item.
  • Please consider catch block to handle unexpected or uncontrolled flow. It is always advisable to avoid exception. For example try to check divide by zero instead of handling it in catch block.
  • Depending on application structure and requirements, we may perform required actions and then may bubble up exception using “throw” statement instead of “throw ex”;
  • We may implement logging for exception.
  • It is highly recommended to decompose a function or method if it is exceeding the visible screen. Rule of thumb is any function should be visible without vertical scroll.
  • We may prefer to make helper classes to perform specific set of operations like: file writing, data converter and etc.
  • Try to avoid value assignment to enum members until unless, these are flagged enums or may have specific purpose like association with database value.
  • Get latest before Check in and make sure that code is compliable before and after check in.
  • Always remove unused namespaces (Context Menu è Organize using è Remove and Sort).
  • It is preferable to reformat code (in Code View using Ctrl + K + D).
  • Use conditional expression in Single, First or FirstorDefault with collection when single item is required.
  • If more than one property is required from a collection object then get that object once from collection, instead of using search for each property.
  • Use Constants or Enums instead of hardcoded values.
  • Use string.Empty instead of “”.
  • If catch does not use Exception object then it is better to omit declaration of Exception.
  • Define required variable at top of scope.
  • Arrange code in regions.
  • Please avoid spelling mistakes.
  • If some item is output of processing and is only required in specific block then better to perform that processing in that block.
  • Remove commented code and unused variables.
  • There should not be any dead or unreachable code sections.
If you are working in C#, then I may recommend you to go through following articles by Microsoft:

Sunday 8 November 2015

Tips for SQL Server Database Design

Database designing is a very vast and very crucial phase. If you belong to group whom goes with Database First Approach, then any decision you make in phase may have huge impacts. I would like to highlight few important points which can be worthy to consider for better database designing and performance.  
  • Always try to device a naming convention and few standards like field size, datatypes, and general assumptions before you start designing database. These can save lot of time and efforts. These can even play vital role in performance.
  • Consider Demoralization, particularly for very large data. But as rule of thumb, first Normalize your Database. It is a good idea to use Indexed view for Demoralization.
  • It will be better to define Primary Key and Foreign Key Relationships.
  • Clearly finalize Database Isolation Level. 
  • Clearly define sequence of involvement to tables in transaction to avoid deadlocks.
  • It is good practice to have one Identity Column in a table, either it is primary key or not.
  • Precisely plan Indexing, and keep in mind, it is ongoing process. Be specific to choose column for clustered and non clustered indexes. In general usage of columns in join, where, order by and group by directly affect your index requirements.
  • You need a good plan for index defragmentation, particularly when there are lots of insert, delete and update operations.
  • Consider new technologies and out of box solution. In general, I may prefer out of box features instead using old custom methodologies until unless there is some specific reason to do so like backward compatibility.
    • Consider built in Table Partitioning feature instead of manual table partitioning for large data tables.
    • Consider File Stream introduced in SQL Server 2008 for File Storage.
    • Consider new DataTypes over old wherever possible, like Varchar(max) over Text, Date over DateTime and etc.
    • Consider In Memory Optimized Tables. Now RAM is very cheap, and such data cache techniques can make a great difference in performance.
  • Consider splitting database into multiple files based on your database size.
  • Consider separation of database files and log files on different hard disk.
  • Always use appropriate datatype, for example if you have to store English data only then you don't need to use nvarchar, or nchar, if you need to store small value set, then there is no need to use bigint.
  • Consider Summary Table or Pre Calculated Data for very large data.
  • Plan a clear strategy for performance and maintenance. In many cases you have to address Performance vs Maintenance. Ideally you must go with some acceptable combination of both, but this decision is directly dependent on your needs and budget.
  • It will be better to same standard for Database objects (Table and Column) and Application Data Model. Although it may not give any performance gain, but it can facilitate developers.
  • If you are planning to use Triggers or Cursors then reevaluate alternate approaches.

Tips for SQL Programing

There are lots of articles on Query Optimization, here I am going to highlight few general points those can make a minor to major difference in performance or quality of code with very little efforts. These are general points, but few things and examples are specifically for SQL Server.
  • Always try to end your SQL statement with semicolon (;).
  • It is preferable to use object name with schema for your tables and other objects. So use dbo.MyTable instead of MyTable.
  • Try to avoid * in Select query, instead use column names. It is better to use Select Coloumn1, Column2, Column3 From dbo.MyTable;
  • It is better to use alias with table name and related columns. So it is better to use with respect to above example: Select tbl.Coloumn1, tbl.Column2, tbl.Column3 From dbo.MyTable as tbl;.
  • Always try to involve as few columns in query as possible. Rule of thumb is not to add columns in query which are not required. 
  • Avoid unnecessary data casting in query.
  • Although SQL Query Optimizer rearrange conditions execution sequence, yet, it is better to add required conditions in Join Statement if applicable.
  • If possible, then consider proper usage of Indexes. If you use an Indexed column with expression (some function, or operator like +, -) then, indexing will not give any benefit as it is ignored in a such case.
  • Avoid Dynamic SQL, in general, stored procedure give better performance. There are few cases where dynamic queries are faster like dynamic sorting, dynamic filters, but dynamic queries may have some other challenges.
  • Try to be specific in database transaction.
  • It should be better to have both operands of same type in a condition.
  • There are many situations, where cursors can be avoided with CTE and loops with temp/memory Table.
  • If you have small data to hold temporary then memory table is better choice over temp table in general.
  • If you are going to fetch data in pages then, fetch and offset is a good option introduced in SQL Server 2012. If you are using SQL Server 2005/2008 then CTE is better approach.
  • Surprisingly, SQL Server do not have short circuit And, OR. It may or may not short circuit your conditions depending on Query Plan.
  • Union All is faster than Union operator. So precisely, use what is required. 
  • Operators OR, Like, In are very expensive operators. There can be alternatives, for example you can use Union All instead of OR.
  • In general if you use Distinct or Group by with out any aggregate function, they will provide same performance. Practically, it will be rare to have both in same query.
  • Please be aware of operator precedence in SQL.
  • It will be better to be aware of latest technologies and features. In general, I may prefer out of box features instead using old custom methodologies until unless there is a reason.
  • If you are going to write a complex sp, and using same data or table again and again, then consider CTE or Temp/Memory Table.

Saturday 31 October 2015

SQL Server Stored Procedure Helper

Few years back, I had a project with very tight timeline and very clear and load objective of performance. We wanted to have optimal performance at database level which were not possible to achieve with any ORM like Entity Framework but due to time constraints, it was also difficult to complete project in time by writing thousands on stored procedure manually.

To standardize and speed up stored procedure writing, I developed a simple application SQL Server Stored Procedure Helper to create basic code for following CRUD operations in no time:
  • Create as Add
  • Read as Get
  • Update
  • Delete
  • and ReadAll as GetAll(additional)

User just have to perform following actions:
  • Run Application
  • Provide Connection String
  • Provide Author Name for Comment
  • Provide prefix for stored procedure name if required
  • Load Database
  • Generate Script
  • Execute Scripts on Database
We have following assumptions:
  • Every table must have Identity Column and that will be Primary key too.
  • For Add and Update operations may work without any change for full object.
  • For Delete operation user may have to handle calls to delete child data as per requirement.
  • For Get operation, user may get standard object for given identity/primary key.
  • For GetAll operation user may have to code joins as per requirements.
You can download full code from following CodePlex Repository: https://ijzsqlserverstoredprocedurehelper.codeplex.com