0% found this document useful (0 votes)
135 views52 pages

Kony Coding Standards

Uploaded by

Jagadeesh J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views52 pages

Kony Coding Standards

Uploaded by

Jagadeesh J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Coding Standards and Best

Practices Guide

Release 6.5
Document Relevance and Accuracy

This document is considered relevant to the Release stated on this title page and the document version
stated on the Revision History page. Remember to always view and download the latest document
version relevant to the software release you are using.

© 2015 by Kony, Inc. All rights reserved 1 of 52


Coding Standards and Best Practices Guide
Version 1.3

Copyright © 2013 Kony, Inc.

All rights reserved.

July, 2015

This document contains information proprietary to Kony, Inc., is bound by the Kony license
agreements and may not be used except in the context of understanding the use and methods of Kony
Inc, software without prior, express, written permission. Kony, Empowering Everywhere, Kony
MobileFabric, Kony Modeler,and Kony Visualizer are trademarks of Kony, Inc. Microsoft, the Microsoft
logo, Internet Explorer, Windows, and Windows Vista are registered trademarks of Microsoft
Corporation. Apple, the Apple logo, iTunes, iPhone, iPad, OS X, Objective-C, Safari, Apple Pay,
Apple Watch and Xcode are trademarks or registered trademarks of Apple, Inc. Google, the Google
logo, Android, and the Android logo are registered trademarks of Google, Inc. Chrome is a trademark
of Google, Inc. BlackBerry, PlayBook, Research in Motion, and RIM are registered trademarks of
BlackBerry. All other terms, trademarks, or service marks mentioned in this document have been
capitalized and are to be considered the property of their respective owners.

© 2015 by Kony, Inc. All rights reserved 2 of 52


Coding Standards and Best Practices Guide
Version 1.3

Revision History

Date Document Description of Modifications/Release


Version

07/11/2015 1.3 Document updated for 6.5 release.

05/12/2014 1.2 Updated for 5.6 release.

© 2015 by Kony, Inc. All rights reserved 3 of 52


Coding Standards and Best Practices Guide
Version 1.3

Table of Contents

1. Preface 5

1.1 Purpose 5

1.2 Intended Audience 5

1.3 Contact Us 6

2. JavaScript Coding Standards 7

2.1 JavaScript Language Rules 13

2.2 Usage of Global and Local Variables 20

2.3 File Names 22

2.4 Readability 23

2.5 Common mistakes 26

3. Logging 32

4. Best Practices in using Widgets 34

5. Error Handling 41

6. Performance 45

6.1 Fast Unordered List Creation 46

7. Universal Coding Standards 47

8. General guidelines 48

9. Useful References 51

© 2015 by Kony, Inc. All rights reserved 4 of 52


1. Preface Coding Standards and Best Practices Guide
Version 1.3

1. Preface

Coding standards and best practices guide is written based on industry standards that help developers
to follow and implement standards throughout software development phase. These standards and
best practices also help to manage the source code consistently.

1.1 Purpose

This document describes the usability of global and local variables, standards, best practices in using
widgets, and error handling. This document explains the coding samples and structure of modules for
developing applications.

1.2 Intended Audience

The intended audience for this document are developers to understand the coding standards and best
practices at Kony.

Formatting conventions

Following are the formatting conventions used throughout the document:

Conventions Explanation

Monospace l User input text, system prompts, and responses

l File path

l Commands

l Program code

l File names

© 2015 by Kony, Inc. All rights reserved 5 of 52


1. Preface Coding Standards and Best Practices Guide
Version 1.3

Conventions Explanation

Italic l Emphasis

l Names of books and documents

l New terminology

Bold l Windows

l Menus

l Buttons

l Icons

l Fields

l Tabs

l Folders

URL Active link to a URL.

Note Provides helpful hints or additional information.

Important Highlights actions or information that might cause problems to


systems or data.

1.3 Contact Us

We welcome your feedback on our documentation. Write to us at [email protected]. For technical


questions, suggestions, comments or to report problems on Kony product line, contact
[email protected].

© 2015 by Kony, Inc. All rights reserved 6 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

2. JavaScript Coding Standards

1. JavaScript is case sensitive.

2. Do not use JavaScript reserved keywords for variable names.

3. Properties and methods:

n Private properties, variables, and methods (in files or classes) should be named with a
trailing underscore.

n Protected properties, variables, and methods should be named without a trailing


underscore (like public ones).

4. Method and function parameters:

n Optional function arguments start with opt_.

n Functions that take a variable number of arguments should have the last argument
named var_args. You may not refer to var_args in the code; use the arguments array.

n Optional and variable arguments can also be specified in @param annotations. Although
either convention is acceptable to the compiler, using both together is preferred.

5. Getters and Setters

n Getters and Setters for properties are discouraged. However, if they are used, then
getters must not change observable state.

/**
* WRONG -- Do NOT do this.
*/
var foo = { get next() { return this.nextId++; } };
};

© 2015 by Kony, Inc. All rights reserved 7 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

6. Accessory functions

n Getters and setters methods for properties are not required. However, if they are used,
then getters must be named getFoo() and setters must be named setFoo(value). (For
Boolean getters, isFoo() is also acceptable, and often sounds more natural.)

7. Namespaces

n JavaScript has no inherent packaging or name-spacing support.

n Global name conflicts are difficult to debug, and can cause intractable problems when two
projects try to integrate. In order to make it possible to share common JavaScript code,
we've adopted conventions to prevent collisions.

8. Use namespaces for global code

n Always prefix identifiers in the global scope with a unique pseudo namespace related to
the project or library. If you are working on "Project Sloth", a reasonable pseudo
namespace would be sloth.*.

var sloth = {};


sloth.sleep = function() {
...
};

Many JavaScript libraries, including the Closure library and Dojo toolkit give you high-
level functions for declaring your namespaces. Be consistent about how you declare your
namespaces.

goog.provide('sloth');
sloth.sleep = function() {
...
};

© 2015 by Kony, Inc. All rights reserved 8 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

9. Respect namespace ownership

n When choosing a child-namespace, make sure that the owners of the parent namespace
know what you are doing. If you start a project that creates hats for sloths, make sure that
the Sloth team knows that you're using sloth.hats.

10. Use different namespaces for external code and internal code

n External code is the code that comes from outside your codebase, and is compiled
independently.

n Internal and external names should be kept strictly separate. If you're using an external
library that makes things available in foo.hats.*, your internal code should not define all its
symbols in foo.hats.*.

foo.require('foo.hats');
/**
* WRONG -- Do NOT do this.
* @constructor
* @extend {foo.hats.RoundHat}
*/
foo.hats.BowlerHat = function() {
};

3. If you need to define new APIs on an external namespace, you should explicitly export the
public API functions, and only those functions.

4. Your internal code should call the internal APIs by their internal names, for consistency
and so that the compiler can optimize them better.

foo.provide('googleyhats.BowlerHat');
foo.require('foo.hats');
/**
* @constructor
* @extend {foo.hats.RoundHat}

© 2015 by Kony, Inc. All rights reserved 9 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

*/
googleyhats.BowlerHat = function() {
...
};
goog.exportSymbol('foo.hats.BowlerHat',
googleyhats.BowlerHat)

11. Alias long type names to improve readability

n Use local aliases for fully-qualified types if doing so improves readability. The name of a
local alias should match the last part of the type.

/**
* @constructor
*/
some.long.namespace.MyClass = function() {
};
/**
* @param {some.long.namespace.MyClass} a
*/
some.long.namespace.MyClass.staticHelper = function(a) {
...

};
myapp.main = function() {
var MyClass = some.long.namespace.MyClass;
var staticHelper =
some.long.namespace.MyClass.staticHelper;
staticHelper(new MyClass());
};

© 2015 by Kony, Inc. All rights reserved 10 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

2. Do not alias namespaces.

myapp.main = function() {
var namespace = some.long.namespace;
namespace.MyClass.staticHelper(new namespace.MyClass());
};
Avoid accessing properties of an aliased type, unless it is
an enum.
/** @enum {string} */
some.long.namespace.Fruit = {
APPLE: 'a',
BANANA: 'b'
};
myapp.main = function() {
var Fruit = some.long.namespace.Fruit;
switch (fruit) {
case Fruit.APPLE:
...
case Fruit.BANANA:
...
}
};

myapp.main = function() {
var MyClass = some.long.namespace.MyClass;
MyClass.staticHelper(null);
};

n Never create aliases in the global scope. Use them only in function blocks.

© 2015 by Kony, Inc. All rights reserved 11 of 52


2. JavaScript Coding Standards Coding Standards and Best Practices Guide
Version 1.3

Note: For more information on function and variable naming standards, see Naming
Standards for Functions and Variables.htm

© 2015 by Kony, Inc. All rights reserved 12 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.1 JavaScript Language Rules

Following are the JavaScript language rules.

2.1.1 Function declaration within blocks

While most of the script engines support Function Declarations within blocks, it is not part of
ECMAScript. Worse implementations are inconsistent with each other and with future ECMAScript
proposals. ECMAScript only allows for Function Declarations in the root statement list of a script or
function. Instead use a variable initialized with a Function Expression to define a function within a
block.

Example:
if (x) {
var foo = function() {}
}
Do not do as below:
if (x) {
function foo() {}
}

If a widget is never shown on a specific platform, set the Render flag to false for that specific platform.
Also, do not access that particular widget in that specific platform as it results in a null pointer
exception.

2.1.2 Standard features

For maximum portability and compatibility, always prefer standards features over non-standard
features (for example: string.charAt(3) over string[3] and element access with DOM functions instead
of using an application-specific shorthand).

© 2015 by Kony, Inc. All rights reserved 13 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.1.3 Closures

ECMAScript (JavaScript) allows inner functions; function definitions and function expressions that are
inside the function bodies of other functions. And those inner functions are allowed access to all of the
local variables, parameters and declared inner functions within their outer functions.

A closure is formed when one of those inner functions is made accessible outside of the function in
which it was contained, so that it may be executed after the outer function has returned. At which point
it still has access to the local variables, parameters and inner function declarations of its outer function.
Those local variables, parameters and function declarations (initially) have the values that they had
when the outer function returned and may be interacted with by the inner function.

One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a result,
attaching a closure to a DOM element can create a circular reference and thus, a memory leak. For
example, observe the following code:

function foo(element, a, b) {
element.onclick = function() { /* uses a and b */ };
}

The function closure keeps a reference to element, a, and b even if it never uses element. Since
element also keeps a reference to the closure, we have a cycle that would not be cleaned up by
garbage collection. In these situations, the code can be structured as follows:

function foo(element, a, b) {
element.onclick = bar(a, b);
}

function bar(a, b) {
return function() { /* uses a and b */ }
}

© 2015 by Kony, Inc. All rights reserved 14 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.1.4 with() {}

Using “with” clouds the semantics of your program. Because the object of the “with” can have
properties that collide with local variables, it can drastically change the meaning of your program. For
example, check the following piece of code:

with (foo) {
var x = 3;
return x;
}

The local variable x could be clobbered by a property of foo and perhaps it even has a setter, in which
case assigning 3 could cause lots of other code to execute. Hence don't use with.

2.1.5 for-in loop

Recommended only for iterating over keys in an object/map/hash.

The 'for-in' loops are often incorrectly used to loop over the elements in an Array. This is however very
error prone because it does not loop from 0 to length - 1 but overall the present keys in the object and
its prototype chain. Here are a few cases where it fails:

function printArray(arr) {
for (var key in arr) {
print(arr[key]);
}
}

printArray([0,1,2,3]); // This works.


var a = new Array(10);
printArray(a); // This is wrong.
a = document.getElementsByTagName('*');
printArray(a); // This is wrong.

© 2015 by Kony, Inc. All rights reserved 15 of 52


Coding Standards and Best Practices Guide
Version 1.3

a = [0,1,2,3];
a.buhu = 'wine';
printArray(a); // This is wrong again.
a = new Array;
a[3] = 3;
printArray(a); // This is wrong again.

Always use normal for loops when using arrays.

function printArray(arr) {
var l = arr.length;
for (var i = 0; i < l; i++) {
print(arr[i]);
}
}

2.1.6 Associative Arrays

Never use Array as a map/hash/associative array.

Associative Arrays are not allowed... more precisely you are not allowed to use non-number indexes
for arrays. If you need a map/hash use Object instead of Array in these cases because the features
that you want are actually features of Object and not of Array. Array just happens to extend Object (like
any other object in JAVASCRIPT and therefore you might as well have used Date, RegExp or String).

2.1.7 Multiline string literals

The following code explains bad string literals.

var myString = 'A rather long string of English text, an error


message \
actually that just keeps going and going -- an error \
message to make the Energizer bunny blush (right through \
those Schwarzenegger shades)! Where was I? Oh yes, \

© 2015 by Kony, Inc. All rights reserved 16 of 52


Coding Standards and Best Practices Guide
Version 1.3

you\'ve got an error and all the extraneous whitespace is \


just gravy. Have a nice day.';

The white space at the beginning of each line cannot be safely stripped at compile time; white space
after the slash will result in tricky errors; and while most script engines support this, it is not part of
ECMAScript.

Use string concatenation instead:

var myString = 'A rather long string of English text, an error


message ' +
'actually that just keeps going and going -- an error ' +
'message to make the Energizer bunny blush (right through ' +
'those Schwarzenegger shades)! Where was I? Oh yes, ' +
'you\'ve got an error and all the extraneous whitespace is ' +
'just gravy. Have a nice day.';

2.1.8 Array and Object literals

Use Array and Object literals instead of Array and Object constructors.

Array constructors are error-prone due to their arguments.

// Length is 3.
var a1 = new Array(x1, x2, x3);
// Length is 2.
var a2 = new Array(x1, x2);
// If x1 is a number and it is a natural number the length will be
x1.
// If x1 is a number but not a natural number this will throw an
exception.
// Otherwise the array will have one element with x1 as its value.
var a3 = new Array(x1);

© 2015 by Kony, Inc. All rights reserved 17 of 52


Coding Standards and Best Practices Guide
Version 1.3

// Length is 0.
var a4 = new Array();

Because of this, if someone changes the code to pass one argument instead of two arguments, the
array might not have the expected length. To avoid these kinds of cases, always use the more
readable array literal.

var a = [x1, x2, x3];


var a2 = [x1, x2];
var a3 = [x1];
var a4 = [];

Object constructors don't have the same problems, but for readability and consistency object literals
should be used.

var o = new Object();


var o2 = new Object();
o2.a = 0;
o2.b = 1;
o2.c = 2;
2['strange key'] = 3;

Should be written as:

var o = {};
var o2 = {
a: 0,
b: 1,
c: 2,
'strange key': 3
};

© 2015 by Kony, Inc. All rights reserved 18 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.1.9 Eval()

Do not use eval() function as it can lead to security issues in the form of code injections.

© 2015 by Kony, Inc. All rights reserved 19 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.2 Usage of Global and Local Variables

1. A variable declared (using var) within a JavaScript function becomes local and can only be
accessed from within that function.

2. If you fail to specify “var”, the variable gets placed in the global context, potentially clobbering
existing values. Also, if there is no declaration, it is hard to tell in what scope a variable lives (for
example: It could be in the Document or Window just as easily as in the local scope). So always
declare with “var”.

3. Use locals rather than globals whenever possible.

//var x = 0 – do not declare variables outside functions


//unless required.
function count(){
var x = 0
x = x + 1
kony.print(x)
}

4. Global variables have application scope and they are not garbage collected unless explicitly
cleared or application exits. Set global variables to null after the usage is completed (equivalent
to “null” in Java)

gblTempVar = null;

5. Widgets have a lot of metadata associated with them and consume a lot more memory to hold
the same amount of data than a global variable.

n For example, kony.store.setItem and kony.store.getItem result in disk I/O and definitely
has much more performance impact than accessing an in memory variable.

n Do not use setItem / getItem or hidden widgets as replacement for global variables.

© 2015 by Kony, Inc. All rights reserved 20 of 52


Coding Standards and Best Practices Guide
Version 1.3

6. Define all the global variables using the global variables section of services tab so that it is easier
to keep a track of them.

n If you want to read a key from a JSON object more than once, it is better to read that key
in a local variable then use it.

n Have a look at the following code snippet:

function validate(){
if (v["headerdesc2"] ~= ""){
innerTable["desc2"] = v["headerdesc2"]
}else{
innerTable["desc2"] = ""
}
}
Better Approach –
function validate(){
var headerValue = v["headerdesc2"]
if (headerValue ~= null and headerValue ~= "" ){
innerTable["desc2"] = headerValue
}else{
innerTable["desc2"] = ""
}
}

© 2015 by Kony, Inc. All rights reserved 21 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.3 File Names

The following file naming conventions must be followed as best practices:

1. File names should be all lowercase in order to avoid confusion on case-sensitive platforms.

2. File names should end in .js, and should contain no punctuation except for - or _ (prefer - to _).

© 2015 by Kony, Inc. All rights reserved 22 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.4 Readability

1. Use Javadoc-like style for commenting.

Example 1:
--[[

*****************************************************
* Name : validateAddress
* Name : validateAddress
* Author : Author name
* Date : 27/05/2010
* Purpose : Deletes the session
* Input : @param id Session identification.

*****************************************************
–]]

function delete (id)


remove (filename (id))
end

2. Provide a comment whenever a construct ends.

for i,v in ipairs(t) do


if type(v) == "string" then
...lots of code here...
end -- if
end -- for

3. Use proper indentation for debugging.

© 2015 by Kony, Inc. All rights reserved 23 of 52


Coding Standards and Best Practices Guide
Version 1.3

4. Use tab indentation for logical blocks.

function makeARemoteDeposit()
local rdcStore = globalStore[ “RDC_STORE” ]
local amount = frmRDCRecap.txtrecapdepamtvalue.text
if(string.len(amount) ==0) then
widget.setvisiblility
(frmRDCRecap.hboxErrorlist,true)
return false
end
end

5. Write proper documentation and comments for each function/module and for typical logic in
functions

6. All wrapped lines must be indented either left to the expression or above or indented four
spaces, except for array and object initializations and passing anonymous functions.

Note: Two space indentation must not be used.

function sample {
someWonderfulHtml = '' +
getEvenMoreHtml(val1,val2,
evenMoreParams, 'a duck',
true, 72,
slightlyMoreMonkeys(0xfff)) +
'';
if (searchableColl(allYourStuff).contains(theStuffYouWant) &&
!ambientNotification.isActive() &&
(client.isAmbientSupported() ||
client.alwaysTryAmbientAnyways())) {
ambientNotification.activate();

© 2015 by Kony, Inc. All rights reserved 24 of 52


Coding Standards and Best Practices Guide
Version 1.3

}
}

© 2015 by Kony, Inc. All rights reserved 25 of 52


Coding Standards and Best Practices Guide
Version 1.3

2.5 Common mistakes

Following is a list of common mistakes to take care of:

1. Do not have cyclic references between JSON objects (Two JSON objects having reference to
each other) as it makes garbage collection difficult.

2. Perform checks for null (for example: variables, mapping segment data etc) and empty string
always before doing any operation on any user input data. This ensures that unexpected results
/ app crashes are avoided.

var myData = kony.store.getItem("friends")


if(myData ~= null) {
// do something
}

local myData = ds.read("friends")


if(myData ~= nil) then
-- do something
end

3. Do not just define strings to null. Initialize strings to either " or ''. If you initialize strings to null,
JavaScript will treat it as string value "null" and all the operations performed on this variable will
get effected.

var name;
var x = null;

x = x + " Bentley Azure"


document.write(x); //null Bentley Azure
document.write(name); // undefined

© 2015 by Kony, Inc. All rights reserved 26 of 52


Coding Standards and Best Practices Guide
Version 1.3

results in
null Bentley Azure
undefined

4. When validating the input, be careful with blank spaces and trim the string.

var holdername = string.trim(frmmCrdtCard.txtcardname.text)


if holdername == null or holdername.length == 0 then
displayAlertMsg("","Please enter card holder
name.",frmmCrdtCard)
clearCardNoAndSecCode(frmmCrdtCard)
return false
end

Better approach: kony.string.trim() will delete the leading and trailing blank spaces of the string.

var holdername = string.trim(frmmCrdtCard.txtcardname.text)


if holdername == null or holdername.length == 0 then
displayAlertMsg("","Please enter card holder
name.",frmmCrdtCard) clearCardNoAndSecCode(frmmCrdtCard)
return false
end

5. Have a look at this code snippet:

var termsDetails = {}
for(v in resulttable["termsset"]){
var innerTable = { termhdr =
resulttable["termsset"][v].headin
resulttable["termsset"][v].p1}
if(resulttable["termsset"][v].p2 ~= ""){

© 2015 by Kony, Inc. All rights reserved 27 of 52


Coding Standards and Best Practices Guide
Version 1.3

innerTable["para2"] = resulttable["termsset"][v].p2
}else{
innerTable["para2"] = ""
}
.
.
if (resulttable["termsset"][v].p16 ~= "" ){
innerTable["para16"] = resulttable["termsset"][v].p16
}else{
innerTable["para16"] = ""
}
termsDetails.push(innerTable)
}
frmTktTermsCond. segTerms .setdata(termsDetails)

Better Approach: For improving the readability and code compactness, you can write the above
code as a lengthy one. Following is an example of lengthy code:

var termsDetails = {};


var termSetList = resulttable["termsset"];
for (v in termSetList) {
var termSet = termSetList[v];
var innerTable = {termhdr = termSet.heading}
for (var idx=1; idx <= 16; idx++){
var rsKeyVal = termSet["p" .. idx]
var seguiKey = "para" .. idx
if(rsKeyVal ~= null and rsKeyVal.length ~= 0) {
innerTable[seguiKey] = rsKeyVal
}else{
innerTable[seguiKey] = ""
}
}

© 2015 by Kony, Inc. All rights reserved 28 of 52


Coding Standards and Best Practices Guide
Version 1.3

termsDetails.insert(innerTable)
}
frmTktTermsCond.segTerms.setdata(termsDetails)

6. If the function returns a value, do not have multiple return statements. Instead, build logic in such
a way that you have only one return at the end of the function.

function getDeepLink(table){
var finalForm = frmLanding
if (table ~= null and table.length ~= 0){
if (table.showscreen ~= null and table.showscreen ~= ""){
for (v in table) {
if (v == "cars" ) {
finalForm = frmCarSearch
}else{
if (v == "hotels" )
finalForm = frmHotelSearch
}
}
}
}
return finalForm
}

7. If you are calling kony.os.toNumber(), ensure that the string you are passing to the function is a
number string that is "5", "3443". Else you will get run-time exceptions.

Example: kony.os.toNumber("34B") --> runtime exception


kony.os.toNumber("55") --> 55 (number is obtained!)

8. Best practice: To avoid run-time exceptions, always use the logic as explained in the following
code:

© 2015 by Kony, Inc. All rights reserved 29 of 52


Coding Standards and Best Practices Guide
Version 1.3

var inputstring = "34B"


if(kony.string.isNumeric(inputstring){
var inputNum = kony.os.toNumber(inputstring);
-- now proceed with functionality
}

9. Avoid writing code outside function blocks. Since Kony platform does not guarantee a specific
order of loading JavaScript files, code written outside function blocks can lead to undefined
errors.

n Write code in function blocks and invoke the same through one of the application
initialization callbacks (preappinit , appinit etc).

10. The name of the form and the module file should not be the same. Since all the files are flattened
when packed into a deployable binary, name clashes should be avoided.

2.5.1 General Guidelines

1. Write logically related functions (functions related to a specific functionality) within a single
module. For example, write all the account summary related functions within or accSummary.js
module.

2. Do the necessary validations in JavaScript before making network calls. For example, check if
the text box has data before invoking a service.

3. Avoid code duplication by writing reusable functions which can be shared across
modules/applications.

4. Write smaller functions (maximum with hundred lines of code) instead of huge monolithic
spaghetti code.

5. Write generalized functions for the tasks that are repetitive across the application.

6. Avoid function calls or expressions (which give the same value in the loops) as these will slow

© 2015 by Kony, Inc. All rights reserved 30 of 52


Coding Standards and Best Practices Guide
Version 1.3

down the loop.

For example:
a = 10;
b = 20;
i = 0;
while(true)
...{
......if (sum(a,b) < i)
......break;
......i++;
...}
//The right way is
a = 10;
b = 20;
c = sum(a,b)
i = 0;
while(true)
...{
......if (c < i)
......break;
......i++;
...}

7. As a good practice, keep the name of input and output variables in either lowercase or
uppercase. Do not mix both the cases. As JavaScript are case sensitive, this helps in making the
development easy and also minimizes the errors.

© 2015 by Kony, Inc. All rights reserved 31 of 52


3. Logging Coding Standards and Best Practices Guide
Version 1.3

3. Logging

Many device SDK loggers in debug mode print a lot of data to the log.

JavaScript

Logging frameworks for JavaScript such as Log4js (which is similar to Java Logging framework Log4j)
can be used to have a robust and solid logging API for efficient logging mechanism.

Use meaningful log statements throughout the code.

--[[
*****************************************************************
* Name : makeServiceCall
* Author : Author Name
* Date : February 19 2010
* Purpose : The purpose of this function to perform a service call.
*****************************************************************
--]]
function makeServiceCall(inputparam)
print("Entering the function makeServiceCall")
print("Making the service call "..inputparam["serviceID"])
local resulttable = appmiddlewareinvoker(inputparam,false,true)
print("Results from the service call "..resulttable)
print("Exiting the function makeServiceCall")
return resulttable
end

Usage of Log4j: Always check if the used log level is enabled instead of directly using it.

package com.kony.custom;
public class CustomPostProcessor implements PostProcessor {
...//Define logger as static final to improve performance
...private static final Logger logger= Logger.getLogger

© 2015 by Kony, Inc. All rights reserved 32 of 52


3. Logging Coding Standards and Best Practices Guide
Version 1.3

(com.kony.custom.CustomPostProcessor .class);
...//Declare the check for debug or info enabled as static final to
improve performance
...private static final boolean isDebugEnabled =
logger.isDebugEnabled();
...private static final boolean isInfoEnabled = logger.isInfoEnabled
();
...public Result execute (Result result, DataControllerRequest
Request) {
......//Wrap logger.debug with isDebugEnabled to improve performance
......if (isDebugEnabled) {
.........logger.debug("This is a debug statement");
......}
......//Wrap logger.info with isInfoEnabled to improve performance
......if (isInfoEnabled) {
.........logger.info("This is an info statement");
......}
...}
}

© 2015 by Kony, Inc. All rights reserved 33 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

4. Best Practices in using Widgets

This section details about the best practices in using Widgets

n Widget Naming Conventions

n Setting the Render flag

n Rich Text

n App Menu

n Segment

n Skins

n Forms

n Releasing Global References held by the form

n API Signature - form.destroy(formId)

n Events - onback Event

n HBox & VBox

n Other Widgets

4.0.1 Widget Naming Conventions

Use the following prefixes for widgets:

Widget Starts with

Form frm

Box hbx, vbx

Tab Pane tbp

© 2015 by Kony, Inc. All rights reserved 34 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

Widget Starts with

Tab tab

Label lbl

Button btn

Text Box txt

Text Area txa

Calendar cal

Combo Box cmb

List Box lst

Check Box chk

Radio Button rbt

Link lnk

Line lin

Image img

Picker View pkv

Menu mnu

Segment seg

Image Gallery igl

Horizontal Image Strip his

Advertisement adv

Phone phn

Camera cam

Switch swt

e.g.(frmSearchResult,btnSearch)

© 2015 by Kony, Inc. All rights reserved 35 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

While naming a widget / form / module / function never go by what gets generated by default in the
IDE. Always give a name that it is meaningful (readable) and maintainable.

1. Use unique names for different elements (forms, widgets, code modules, images, and skins)
within an application. For example, do not use the skin names as any form or variable names in
the application. Using the same name in variable names would cause overwriting the skin with
the variable. If you follow proper naming convention for different widgets this problem does not
arise.

Ensure that the widgets that are accessible from code follow a proper naming convention. Retaining
the auto generated names make it difficult to keep track of the widgets and their parent.

4.0.2 Setting the Render flag

If a widget is never shown on a specific platform, set the Render flag to false for that specific platform.
Also, do not access that particular widget for that specific platform (this results in null pointer
exception).

4.0.3 Rich Text

Avoid unnecessary use of rich-text widget, as it is a heavy widget.

4.0.4 App Menu

1. Avoid making network calls or huge logic execution while switching over app menu items. App
menu switching should be instantaneous and smooth as executing lot of logic over there doesn’t
give good look and feel.

2. Set appmenufocusedindex to the required menu item when flow changes.

Example: If the user moves from Dashboard to Transfer flow (assuming Dashboard as

© 2015 by Kony, Inc. All rights reserved 36 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

the 1st menu item, Transfer as 2nd menu item) then set the index as
setappmenufocusedindex(2)

4.0.5 Segment

1. (iPhone) If Segmented UI widget consists of more than 5 widgets and if there are more than 10
records in the segment then make it as screen level widget and ensure that remaining widgets
on the screen are headers and footers – This will result in memory optimizations such as re-
using the rows for representing different data sets etc. This is the reason most of the iPhone
native apps have one segmented UI per screen holding any number of records. You will rarely
see – two segmented UI widgets on one screen each one holding huge number of rows.

2. Using more than one segmented UI widget on one screen is a non-optimized design.

3. segui.setdata on segmented UI is costly and will erase all the data of the segment and set it
again. Avoid calling it repeatedly/unnecessarily in for loops. Instead use segui.setdataat or
segue.addat functions

Example of bad code:

local segdata = {}
for i,v in ipairs(somedataset)
...segdata[i] = v;
...segui.setdata(formid.seguid,segdata);
end

Example of good code:

local segdata = {}
for i,v in ipairs(somedataset)
...segdata[i] = v;
end
segui.setdata(formid.seguid,segdata);

© 2015 by Kony, Inc. All rights reserved 37 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

4. Call segmentedUI widgetdatamap() only once. It could be better if you keep this code in form's
master-data-load/transactional-data-load events.

4.0.6 Skins

1. Do not create too many skins. It is better to create a template and your team can reuse.

2. Try to use a theme for the application.

3. It is very important to create and use Focus skins. This becomes an absolute necessity on non-
touch devices.

4. While using Dynamic skinning reference the skin as an object, not a string.

Example: For a Phone Widget, if you want to display different skins for successful and
unsuccessful dial attempts.

function clickphone()
local retvalue = phone.dial("555-2368")
if retvalue == -1 then -- a failure
myForm.myPhone.skin = errorskin
else
myForm.myPhone.skin = successskin
end
end

4.0.7 Forms

1. Use pre-show event for making widgets visible/invisible. Avoid service calls on a pre-show
event.

2. Use post-show when a long running service call is to be executed while the form is shown
(shown in a disabled state) to the end user.

© 2015 by Kony, Inc. All rights reserved 38 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

3. Try to avoid setting data in more than 2/3 forms as loading all these forms may take time due to
which user experience will be bad as the action/showing the required form may take long time.
Better to set the text just before display of the respected form.

4. Do not use form.show() in the form's pre/post show functions.

5. Do not use the names of the form as the name of the code module because the form is also
converted to script files and will conflict with the code modules during compilation of the code.

6. Try to avoid form forking unless you require a completely different form for another platform.
When you fork the forms, make sure all the widgets in the forked form are present in the parent
form in a hidden state. This is because if they are not available in the parent form, you cannot
map data to widgets in the forked form using Mapping Editor.

4.0.8 Releasing Global References held by the form

form.destroy – if called destroys the form’s state and the widgets state. If the same form is revisited, it
will be initialized again. Forms like Terms & conditions, Maps, and Help can be destroyed.

4.0.9 API Signature - form.destroy(formId)

Developer should access the form’s data or its widgets as and when required (Lazy access). Calling
destroy method on the same form more than once doesn’t have any impact on the application.

4.0.10 Events - onback Event

n onback event is used to destroy the unwanted form. It is available in Andriod, BB platforms.

n Current form indicates the form where the user is in, when on low memory event is raised.

onlowmemory(currentform)

4.0.11 HBox & VBox

Use hboxes/vboxes carefully.

© 2015 by Kony, Inc. All rights reserved 39 of 52


4. Best Practices in using Widgets Coding Standards and Best Practices Guide
Version 1.3

If there is a single widget (for example: Label, Button etc) to be placed in a container, place it directly
on the container (for example, form) instead of using HBox/VBox.

Wrong:

Correct:

We can remove above hbox in segUI by changing the segUI orientation to Horizontal

<There are more examples (image illustrations) in the source and dependent document>

4.0.12 Other Widgets

All Selection widgets ( ListBox, ComboBox, and CheckBoxGroup)

1. selectedkeys is a write only property. Do not use it to read the selected keys.

2. Do not have any processor intensive tasks like service calls in the onslide event of a slider
widget.

3. For a picker view the widths of all the components need to add up to hundred if you are setting
width dynamically through code. If the width is not adding up to hundred a run time error
appears.

© 2015 by Kony, Inc. All rights reserved 40 of 52


5. Error Handling Coding Standards and Best Practices Guide
Version 1.3

5. Error Handling

1. The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally constructs as well as the throw operator to handle exceptions.

2. You can catch programmer-generated and run-time exceptions, but you cannot catch
JavaScript syntax errors.

3. Following is the try...catch...finally block syntax:

<script type="text/javascript">
<!--
try {
// Code to run

} catch ( e ) {
// Code to run if an exception occurs

}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

4. Following is an example demonstrating usage of try, catch and finally (The code is using a non
existent method "MyAlert", hence leading to an exception, but by placing try, catch and finally
handling the exception)

<html>
<head>
<script type="text/javascript">

© 2015 by Kony, Inc. All rights reserved 41 of 52


5. Error Handling Coding Standards and Best Practices Guide
Version 1.3

<!--
function myFunc()
{
var a = 100;

try {
MyAlert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + e.description );
}finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

5. The throw statement allows you to create or throw an exception. You can use the throw
statement together with try and catch to control program flow and generate custom error
messages.

6. The following code is an example on usage of throw. The code examines the value of an input
variable. If the value is wrong, an exception (error) is thrown. The error is caught by the catch
statement and a custom error message appears.

© 2015 by Kony, Inc. All rights reserved 42 of 52


5. Error Handling Coding Standards and Best Practices Guide
Version 1.3

<!DOCTYPE html>
<body>
<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "to high";
if(x<5) throw "too low";
alert("You entered: "+x);
}
catch(err)
{
alert("Error: " + err + ".");
}
}
</script>

<h1>JavaScript Exception Handling</h1>


<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test
Input</button>

</body>
</html>

© 2015 by Kony, Inc. All rights reserved 43 of 52


5. Error Handling Coding Standards and Best Practices Guide
Version 1.3

Note:
1. Define a function or global sequence for error handling of the service calls and handle all
the basic error codes returned by Kony Application Server.
2. Ensure you write proper code to handle errors returned by network calls.

© 2015 by Kony, Inc. All rights reserved 44 of 52


6. Performance Coding Standards and Best Practices Guide
Version 1.3

6. Performance

1. Use pre/post processors as much as possible for formatting service request / service response.

2. Avoid complicated algorithms like sorting on huge number of results (say records in the order of
100’s) on the device. It is preferable to do the same on the server.

3. Avoid multiple timers, instead use multiple flags with a single timer ticking and different action
being performed on the basis of state of various flags.

4. Memory allocation from the heap--e.g. repeatedly creating tables can slow down.

5. Short inline expressions can be faster than function calls. t[#t+1] = 0 is faster than table.insert(t,
0).

6. Constant folding: x * (1/3) is just as fast as x * 0.33333333333333333.

7. Multiplication x*0.5 is faster than division x/2.

8. x*x is faster than x^2.

9. For loops are quite a bit faster than while loops.

10. Have a look at the below code snippet:

if(gcurrentpage == "Car%20Member%20RegisteredCC"
or gcurrentpage == "Car%20Confirmation"
or gcurrentpage == "Car%20DriverNameMismatch"
.
.
or gcurrentpage == "Privacy%20Policy%20details") then
secure = true
end
Better Approach – Here table lookup works faster compared to
"or"ing so many times and in this particular case.

© 2015 by Kony, Inc. All rights reserved 45 of 52


6. Performance Coding Standards and Best Practices Guide
Version 1.3

Note: If the block is executed several times during the


application's flow, the memory overhead of creating a global
hash table (gCurrentPageDict) is justified as it improves the
performance each time the block is executed.
gCurrentPageDict = {}
gCurrentPageDict["Car%20Member%20RegisteredCC"] = true
gCurrentPageDict["Car%20Confirmation"] = true
gCurrentPageDict["Car%20DriverNameMismatch"] = true
.
.
gCurrentPageDict["Privacy%20Policy%20details"] = true
if(gCurrentPageDict[gcurrentpage]) then
secure = true
end

6.1 Fast Unordered List Creation

table = { "harold", "victoria", "margaret", "guthrie" }


for i=1, getn(table) do
-- do something with table[i]
end

However, if we are not concerned about element order, the above iteration is slow. The first problem is
that it calls getn(), which has order O(n) assuming as above that the "n" field has not been set. The
second problem is that bytecode must be executed and a table lookup performed to access each
element (that is, "table[i]").

A solution is to use a table iterator instead:

for x, element in pairs(table) do


-- do something with element
end

© 2015 by Kony, Inc. All rights reserved 46 of 52


7. Universal Coding Standards Coding Standards and Best Practices Guide
Version 1.3

7. Universal Coding Standards

For Server side programming in Java, follow the universal coding standards available at
http://www.oracle.com/technetwork/java/codeconventions-150003.pdf

© 2015 by Kony, Inc. All rights reserved 47 of 52


8. General guidelines Coding Standards and Best Practices Guide
Version 1.3

8. General guidelines

1. Strings: For consistency single-quotes (') are preferred to double-quotes ("). This is helpful
when creating strings that include HTML:

var msg = 'This is some HTML';

2. Be aware that the following are all false in Boolean expressions:

n Null

n Undefined

n '' the empty string

n 0 the number

3. Following are all true in Boolean expressions:

n '0' the string

n [] the empty array

n {} the empty object

4. Ensure the outcome of Boolean expressions is implemented properly for all scenarios.

Following are few examples:

while (x != null) {

Instead of the above expression, you can write the following shorter code (as long as you do not
expect 'x' to be 0, or the empty string, or false):

while (x) {

If you want to check a string to see if it is null or empty, you could do the following:

if (y != null && y != '') {

© 2015 by Kony, Inc. All rights reserved 48 of 52


8. General guidelines Coding Standards and Best Practices Guide
Version 1.3

But this is shorter and nicer:

if (y) {

5. Conditional (Ternary) Operator (?:)

n Use Conditional operator if applicable. Instead of the following:

if (val != 0) {
return foo();
} else {
return bar();
}

You can write this:

return val ? foo() : bar();

The ternary conditional is also useful when generating the HTML.

var html = '<input type="checkbox"' +


(isChecked ? ' checked' : '') +
(isEnabled ? '' : ' disabled') +
' name="foo">';

6. Iterating over lists

When iterating over Lists, avoid iterating over the list by re-checking the length with every
iteration.
Instead of writing code as:

var paragraphs = document.getElementsByTagName('p');


for (var i = 0; i < paragraphs.length; i++) {
doSomething(paragraphs[i]);
}

It is better to do the following:

© 2015 by Kony, Inc. All rights reserved 49 of 52


8. General guidelines Coding Standards and Best Practices Guide
Version 1.3

var paragraphs = document.getElementsByTagName('p');


var paragraphsSize = paragraphs.length;
for (var i = 0; i < paragraphsSize; i++) {
doSomething(paragraphs[i]);
}

General points to remember

1. Avoid saving empty table using ds.save() as this empty table does not work in Android platform.

2. Make window.showloadingscreen as blocking unless it is specifically required that the user must
be able to select the UI elements while the network call is in progress.

3. The blockUI parameter in the service calls is applicable only for Mobile Web. For native
applications, use window.showloadingscreen API to block the UI.

4. The window.Alert must be the last statement in an execution flow as it is not a non-blocking call.

5. Try to avoid setting static text in code and sending the same as input to the service. For
example, if some of the static text changes in order to implement a change, you have to modify
the application and re-submit to Apple for its approval. Think on pre-processors for the static text
that can be assigned to the request params before sending it to the client or vendor's site.

6. setappmenu() must be called only once and must be called in pre-appinit event.

7. Use popup.dismiss() rather than popup.destoy(), if popup is required to be hidden from the
screen. If popup.destroy() is called, the data and the pop-up contexts will be released from
memory.

8. The idle timeout defined for the form should be less than the memcache.expiry which is
specified in the middeware.properties file in the server.

Note: The idle timeout is set in minutes and the memcache expiry time is in seconds.

© 2015 by Kony, Inc. All rights reserved 50 of 52


9. Useful References Coding Standards and Best Practices Guide
Version 1.3

9. Useful References

n http://sputnik.freewisdom.org/en/Coding_Standard

Sun Java Coding Conventions

n http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

JDepend (Dependency analyzer)

Update Site URL:

n http://andrei.gmxhome.de/eclipse/

Checkstyle

Update Site URL:

n http://eclipse-cs.sf.net/update/

PMD

Update Site URL:

n http://pmd.sourceforge.net/eclipse

JIndent

Update Site URL:

n http://downloads.jindent.com/plugins/eclipse/3.x/

Jprobe

Update Site URL:

For 3.4

n http://www.quest.com/jprobe/Eclipseupdate/

© 2015 by Kony, Inc. All rights reserved 51 of 52


9. Useful References Coding Standards and Best Practices Guide
Version 1.3

For 3.5

n http://www.quest.com/jprobe/Eclipseupdate/35

Hammurapi

Web URL :

n http://marketplace.eclipse.org/content/hammurapi-code-review-plug

© 2015 by Kony, Inc. All rights reserved 52 of 52

You might also like