Kony Coding Standards
Kony Coding Standards
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.
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.
Revision History
Table of Contents
1. Preface 5
1.1 Purpose 5
1.3 Contact Us 6
2.4 Readability 23
3. Logging 32
5. Error Handling 41
6. Performance 45
8. General guidelines 48
9. Useful References 51
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.
The intended audience for this document are developers to understand the coding standards and best
practices at Kony.
Formatting conventions
Conventions Explanation
l File path
l Commands
l Program code
l File names
Conventions Explanation
Italic l Emphasis
l New terminology
Bold l Windows
l Menus
l Buttons
l Icons
l Fields
l Tabs
l Folders
1.3 Contact Us
n Private properties, variables, and methods (in files or classes) should be named with a
trailing underscore.
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.
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++; } };
};
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 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.
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.*.
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() {
...
};
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}
*/
googleyhats.BowlerHat = function() {
...
};
goog.exportSymbol('foo.hats.BowlerHat',
googleyhats.BowlerHat)
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());
};
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.
Note: For more information on function and variable naming standards, see Naming
Standards for Functions and Variables.htm
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.
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).
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 */ }
}
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.
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]);
}
}
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.
function printArray(arr) {
var l = arr.length;
for (var i = 0; i < l; i++) {
print(arr[i]);
}
}
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).
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 Array and Object literals instead of Array and Object constructors.
// 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);
// 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.
Object constructors don't have the same problems, but for readability and consistency object literals
should be used.
var o = {};
var o2 = {
a: 0,
b: 1,
c: 2,
'strange key': 3
};
2.1.9 Eval()
Do not use eval() function as it can lead to security issues in the form of code injections.
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”.
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.
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.
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"] = ""
}
}
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 _).
2.4 Readability
Example 1:
--[[
*****************************************************
* Name : validateAddress
* Name : validateAddress
* Author : Author name
* Date : 27/05/2010
* Purpose : Deletes the session
* Input : @param id Session identification.
*****************************************************
–]]
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.
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();
}
}
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.
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;
results in
null Bentley Azure
undefined
4. When validating the input, be careful with blank spaces and trim the string.
Better approach: kony.string.trim() will delete the leading and trailing blank spaces of the string.
var termsDetails = {}
for(v in resulttable["termsset"]){
var innerTable = { termhdr =
resulttable["termsset"][v].headin
resulttable["termsset"][v].p1}
if(resulttable["termsset"][v].p2 ~= ""){
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:
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.
8. Best practice: To avoid run-time exceptions, always use the logic as explained in the following
code:
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.
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
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.
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.
--[[
*****************************************************************
* 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
(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");
......}
...}
}
n Rich Text
n App Menu
n Segment
n Skins
n Forms
n Other Widgets
Form frm
Tab tab
Label lbl
Button btn
Calendar cal
Link lnk
Line lin
Image img
Menu mnu
Segment seg
Advertisement adv
Phone phn
Camera cam
Switch swt
e.g.(frmSearchResult,btnSearch)
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.
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).
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.
Example: If the user moves from Dashboard to Transfer flow (assuming Dashboard as
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
local segdata = {}
for i,v in ipairs(somedataset)
...segdata[i] = v;
...segui.setdata(formid.seguid,segdata);
end
local segdata = {}
for i,v in ipairs(somedataset)
...segdata[i] = v;
end
segui.setdata(formid.seguid,segdata);
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.
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.
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.
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.
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.
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.
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)
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>
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.
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.
<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">
<!--
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.
<!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>
</body>
</html>
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.
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).
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.
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]").
For Server side programming in Java, follow the universal coding standards available at
http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
8. General guidelines
1. Strings: For consistency single-quotes (') are preferred to double-quotes ("). This is helpful
when creating strings that include HTML:
n Null
n Undefined
n 0 the number
4. Ensure the outcome of Boolean expressions is implemented properly for all scenarios.
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) {
if (val != 0) {
return foo();
} else {
return bar();
}
When iterating over Lists, avoid iterating over the list by re-checking the length with every
iteration.
Instead of writing code as:
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.
9. Useful References
n http://sputnik.freewisdom.org/en/Coding_Standard
n http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
n http://andrei.gmxhome.de/eclipse/
Checkstyle
n http://eclipse-cs.sf.net/update/
PMD
n http://pmd.sourceforge.net/eclipse
JIndent
n http://downloads.jindent.com/plugins/eclipse/3.x/
Jprobe
For 3.4
n http://www.quest.com/jprobe/Eclipseupdate/
For 3.5
n http://www.quest.com/jprobe/Eclipseupdate/35
Hammurapi
Web URL :
n http://marketplace.eclipse.org/content/hammurapi-code-review-plug