0% found this document useful (0 votes)
11 views

Coding for Beginners, 2020

This document provides comprehensive guidance on coding best practices, particularly focusing on Java performance tuning, coding standards, and advanced strategies for various programming languages including JavaScript and ASP.NET. It covers essential topics such as object creation, exception handling, loops, collections, and string manipulation, emphasizing the importance of optimizing code for better performance and maintainability. The content is structured into chapters, each addressing specific aspects of coding practices and performance enhancement techniques.
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)
11 views

Coding for Beginners, 2020

This document provides comprehensive guidance on coding best practices, particularly focusing on Java performance tuning, coding standards, and advanced strategies for various programming languages including JavaScript and ASP.NET. It covers essential topics such as object creation, exception handling, loops, collections, and string manipulation, emphasizing the importance of optimizing code for better performance and maintainability. The content is structured into chapters, each addressing specific aspects of coding practices and performance enhancement techniques.
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/ 163

Coding for Beginners

Advanced Methods and


Strategies to Learn the Best
Coding Practices
© Copyright 2020 by Alexander Cane - All rights reserved.
This document is geared towards providing exact and reliable
information in regards to the topic and issue covered. The
publication is sold with the idea that the publisher is not required to
render accounting, officially permitted, or otherwise, qualified
services. If advice is necessary, legal or professional, a practiced
individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved
equally by a Committee of the American Bar Association and a
Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of
this document in either electronic means or in printed format.
Recording of this publication is strictly prohibited, and any storage of
this document is not allowed unless with written permission from the
publisher. All rights reserved.
The information provided herein is stated to be truthful and
consistent, in that any liability, in terms of inattention or otherwise, by
any usage or abuse of any policies, processes, or directions
contained within is the solitary and utter responsibility of the recipient
reader. Under no circumstances will any legal responsibility or blame
be held against the publisher for any reparation, damages, or
monetary loss due to the information herein, either directly or
indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely
and is universal as so. The presentation of the information is without
a contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the
publication of the trademark is without permission or backing by the
trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are owned by the owners themselves,
not affiliated with this document.
Table of Content
Chapter 1: Methods and Strategies for Java Performance Tuning
Introduction
Creating Objects
Exceptions
Casts and Variables
Loops and Switches
Collection
Strings
Best Practices
Java Code Tuning for Optimum Performance
Memory Management for Optimum Performance
Chapter 2: Advanced Strategies for Improving Java Code
Performance
Introduction
Best Practices to Avoid Common Mistakes while Coding
Tips for Developing the Java Application Using MySQL and MULE
Chapter 3: Best Coding Practices for Java Programming
Introduction
Best Coding Practices
Advanced Tips in Java
Chapter 4: Coding Standards for Programming
Introduction
Naming Conventions
Hard-Coded Values
Code Format
Java Source File Style
Class
Class Fields
Constructors
Accessor Methods
Other Methods
Documentation for “Javadoc”
Java Comments
Chapter 5: Best Design Practices in Java
Application Design
Coding Design
Chapter 6: Best Practices in Java Swing
Application Design Best Practices
Functionality
Programming Best Practices
Painting Guidelines
Performance Tips
Chapter 7: Best Coding Practices for JavaScript
Performance Tuning
Caching Scripts
Caching Objects
Lazy Initialization
Don’t Use Eval
Pre Calculate Loop’s Length
Tuning in String Manipulations
Eliminate Unnecessary Variables
Declare and Assign a Variable in a Single Statement
Debugging Strategies for Javascript
JavaScript Useful Strategies and Methods
Chapter 8: Best Practices for JavaScript and ExtJS
Project Organization
Naming Conventions
Code Style Conventions
Development Guidelines
ExtJS Development Tips
Enabling Re-Use in ExtJS
Performance Tips
Useful Tips and Techniques for HTML/JavaScript Developers
Chapter 9: Coding Tips and Best Practices for Asp.Net Web
Application
StringBuilder Class over String
Session State Usage
Server-Side Vs. Client-Side Validation
ViewState and ControlState
Option Strict and Option Explicit
Turn Tracing and Debugging Off
Debugging Tips for Dot Net Application
Chapter 10: Advanced Strategies for Enhancing ASP.NET
Performance
String Management
Turn Off Session State
Using View State
Separation of Content and Logging
Constrain Unwanted Web Server Traffic
Exception Management
Window Forms Optimization In .Net
Chapter 11: Mobile App Development Using Android Studio and
Sencha
IntelliJ IDEA
Structure of IntelliJ IDEA
Basic Understanding of Android Studio over Eclipse IDE
Sencha Cordova App - Tips and Tricks
Backbase Mobile SDK
Solving Problems with App Development
Conclusion
Chapter 1: Methods and Strategies for Java
Performance Tuning

Introduction
Performance has been an important factor for software developers.
Java Performance tuning means optimizing the code to obtain a
faster, more reliable, scalable, and easily maintainable code. This is
a very important aspect because the code written by you should be
very fast and maintainable, otherwise it not of any use.
Generally, it is best to keep your knobs off as far as Java tuning is
concerned. Most applications, whose performance is required to be
improved, can be improved by simply keeping the development
environment up-to-date! We will discuss various aspects of tuning.
Java performance tuning is a very vast topic, and as such, no
document can contain the complete information. First, we will
observe certain best practices that may improve your Java
application’s performance. Then, we will mention the various
improvements which could be made within your Java code.
Following Java performance tips provides all the details a developer
needs for performance tuning of the Java code.
Creating Objects
1. We need to create Objects before they can be used, and
needs to be garbage-collected when they are no longer
needed.
2. When we use more objects, the more garbage-cycling
happens so that the CPU cycle gets wasted.
3. Reduce the temporary objects which are getting used
inside the loops.
4. Try to avoid the creation of temporary objects inside the
methods which are called more frequently in the program.
5. Collection objects should be pre-sized beforehand only.
6. Objects should be reused wherever it is possible to do so.
7. Empty the collection objects in case it is required to reuse
them at a later stage.
8. Reduce the number of objects being created inside the
loop since creating objects costs both time and additional
memory utilization.
9. There are certain objects which return a copy of an object,
or some methods do not return a copy.
For example, String.trim() returns a new object and methods like
Vector.setSize() does not return a copy. So if you do not require a
copy, use/create methods that do not copy the objects.
For example:
String str = "";
While(Condition) {
//...
str += appendingString1;
}
It will creates a new String object on each += operation (plus a
StringBuilder and the new underlying char array), we can rewrite this
into:
Example:
StringBuilder strB = new StringBuilder();
While(Condition){
//...
strB.append(appendingString1);
}
String str = strB.toString();

Try to avoid initializing instance variables more than one time.


Try to Use the clone () method to avoid calling constructors.
Many objects need to be created and initialized, and many of these
objects will be used later, but not immediately. In this case, it can be
useful to spread out a load of object initialization so we don't use to
get one large hit on the application.

Example:
package com.rule;
public class Do_lazy_initialization_violation
{
private Do_lazy_initialization_violation instance = new
Do_lazy_initialization_violation(); //Violation
}
Should be written as:
package com.rule;
public class Do_lazy_initialization_correction
{
private Do_lazy_initialization_violation instance;
public Do_lazy_initialization_violation getInstance()
{
if(doLazy == null)
instance = new Do_lazy_initialization_violation(); // Correction
return instance;
}
}
Exceptions
Include all error-condition checking in blocks surrounded by if, if-else
statements.
1. Avoid the use of Generic class exception inside the catch
block. Instead, you can use the particular catch block for
every try block based upon the error you might get in your
program.
2. Avoid the use of exception handling when it is not inside
the control flow of the program.
3. Try to minimize the use of exception handling unless there
is a chance of exception going to happen in the code.
4. Always use the exact subclass of your exception while
using the “throws” method. It should be
ArrayIndexOutOfBoundsException or
FlieNotFoundException instead of using Exception.
5. Exception handling should be avoided inside the loops. Try
to place the loops in the try/catch blocks only.
6. Prefer to use ‘StringBuilder’ instead of ‘StringBuffer’ as it
avoids the cost of internal synchronization.
7. Be cautious when working with String concatenation
operations. Choose to use either ‘+’ or
‘StringBuilder.append’ appropriately based upon the
requirement. If concatenation of a few items is required,
use ‘+.’ If there is a large set of items to be concatenated,
then use the ‘append’ method of StringBuilder. It improves
the performance greatly in case of a larger item set
concatenation.
8. Relying on the ‘finalize’ method to reclaim resources is a
bad practice. Even if a ‘finalize’ method is defined, the
programmer should define another way of releasing the
resources as the finalize method will be called just before
the garbage collection and not when the object is out-of-
scope.
9. The use of finally block is a must to release the memory
resources used in the connection, or closing the file to
minimize the risk of exception getting raised at a later
stage.
10. Reuse an existing Exception object instead of creating a
new one. However, the main disadvantage of reusing the
exception object is that instance does not have the correct
stack trace, i.e., it is the one generated when the exception
object was created.
11. While doing the casting, if you use the try-catch block, it will
be slower, but if you use the “instanceof,” it will be much
faster.
Example:
package com.performance.exception;
public class ExceptionTest1{
public static void main(String args[]){
long start,end;
int i = 0;
int[] intArray = new int[25000];
String stringArray[] = new String[25000];
int size = stringArray.length;
for(i = 0; i < size ; i++){
if(i % 50 == 0)
stringArray[i] = "hello world";
else
stringArray[i] = Integer.toString(i);
}
start = System.currentTimeMillis();
for( i = 0; i < size; i++){
try{
intArray[i] = Integer.parseInt(stringArray[i]);
}catch(NumberFormatException e){}
}
end = System.currentTimeMillis();
System.out.println(end - start + " millis with try/catch inside the for
loop ");
start = System.currentTimeMillis();
try {
for( i = 0 ; i < size; i++){
intArray[i] = Integer.parseInt(stringArray[i]);
}
}
catch(NumberFormatException e){}
end = System.currentTimeMillis();
System.out.println(end - start + " millis with try/catch outside the for
loop ");
}
}

The output is as follows:


50 millis with try/catch inside for loop
0 millis with try/catch outside for loop
Casts and Variables
1. Try to avoid the typecasting by using simple collection
types.
2. Try to use temporary variables in the case of cast typing,
rather than repeatedly casting it.
3. We have to use the Type variables in a precise manner.

4. We have to use local variables more in the program


instead of static or instance variables to get faster results
and manipulation.
5. Try to avoid using long, double instance, and static
variables.
6. Prefer to use primitive data types rather than other
temporary variable objects.
7. Use local variables instead of instance or static variables
since local variables are faster to manipulate.
Loops and Switches
1. Always make the loop functionality as little as possible to
enhance the performance.
2. Consider removing from the loop the execution code that
does not require to be executed each time.
3. Move any repeatedly executed code that causes the same
result and assign it to a temporary variable before the loop
calls.
4. Avoid method calls inside the loops when possible, even if
this needs to rewriting or inlining.
5. If possible, avoid using such methods like length (), size (),
etc. If we use method calls inside the loop condition
statement, it can cause a performance hit.
6. Avoid placing exception handling code (try-catch-finally)
inside loops. Instead, place loops inside try-catch, which
results in better performance.
7. Avoid calling methods inside a loop as far as possible as
method calls are very costly operations. Also, avoid using
method calls to check for the termination condition in loops.
Example:
package com.rule;
class Avoid_method_calls_in_loop_violation1
{
public void method()
{
String str = "Hello world";
for (int i = 0; i < str.length(); i++) // VIOLATION
{
i++;
}
}
}
Should be written as:
package com.rule;
class Avoid_method_calls_in_loop_correction1
{ public void method()
{
String str = "Hello world ";
int len = str.length(); // CORRECTION
for (int i = 0; i < len ; i++)
{
i++;
}
}
}
Try to use int data types preferably for the loop variable.
Always use System.arraycopy( ) to copy arrays.
Use Convert equality comparisons to identity comparisons.
Avoid unneeded temporary variables inside loops.

Example:
package com.performance.loop;
// This class tests the loop copy versus System.arraycopy()
public class loopTest1{
public static void main(String s[]){
long start,end;
int[] a = new int[2500000];
int[] b = new int[2500000];
for(int i = 0; i < a.length; i++){
a[i] = i;
}
start = System.currentTimeMillis();
for(int j = 0; j < a.length; j++){
b[j] = a[j];
}
end = System.currentTimeMillis();
System.out.println(end - start + " milli seconds for loop copy
display");
int[] c = new int[2500000];
start = System.currentTimeMillis();
System.arraycopy(a, 0, c, 0, c.length);
end = System.currentTimeMillis();
System.out.println(end - start + " milli seconds for
System.arraycopy() display");
}
}

The output is
110 milliseconds for loop copy display
50 milliseconds for System.arraycopy() display
Rewrite switch statements to use a contiguous range of cases.
We have to identify whether a recursive method can be done faster.
Change recursive methods to use iteration.
Always caching recursively calculated values in case of reducing the
depth of recursion.
Collection
1. Try to pre-size collections to their required sizes when
possible.
2. Consider switching for alternative data structures and
algorithms when possible.
3. Always prefer the most appropriate collection class.

4. Always compare using two collections with different


performance perspective to hold the same data.
5. We have to consider using plain arrays like String[].

6. We need to select specialized collections to avoid casts


and unnecessary method calls.
7. Allocate the required memory for element storage in prior
instead of allocating at run time.
8. Always use Buffered Streams rather than using just the
FileInputStream and FileOutputStreams and always close
the stream. This is because FileInputStream and
FileOutputStream take the data byte by byte and copies it
to the destination. BufferedInputStream and
BufferedOutputStream batch the requests to improve
performance.
Strings
Avoid creating a String object using the ‘new’ keyword and prefer to
create a String literal if the content is the same. String literals hold
good when compared to String objects in performance.
String.equals() method:

Checks for Object identity


Checks for null
Checks for String Type
Checks for Size
Checks each character one by one

String.equalsIgnoreCase() method:

Checks for null


Checks for size
Case insensitive comparison character by character by
running regionMatches(), converting each character to
uppercase before comparing.
The equals() method runs much faster than
equalsIgnoreCase() if the strings are identical since it does
an identity check. An identity check is basically a pointer
reference check. Whereas equalsIgnoreCase() method
runs much faster than equals() method when the two
strings are different in sizes since then equalsIgnoreCase()
needs to run only two checks and equals() method needs
to run four checks before they return any value.
When a string can be resolved at compile-time, use the
concatenation operator (+) but when a string can be resolved at
runtime StringBuffer is more efficient.
Avoid the use of StringTokenizer.
Example:
package com.rule;
class Avoid_using_StringTokenizer_violation1
{
public void method(String str)
{
StringTokenizer strtok = new StringTokenizer(str); // VIOLATION
while(strtok.hasMoreTokens())
{
System.out.println(strtok.nextToken());
}
}
}
Should be written as:
package com.rule;
class Avoid_using_StringTokenizer_correction1
{
public void method(String str)
{
String[] parts = breakUp(str); // CORRECTION
int len = parts.length;
for(int i = len; i > 0; i--)
{
System.out.println(parts[len - i]);
}
}

String[] breakUp(String str)


{
String strParts[];
// break the string into parts
return strParts;
}
}
Try to use efficient methods of String that don’t copy the characters
of the string, like String.substring().
Avoid using String methods that used to copy the characters of the
string, like String.toUppercase() and String.toLowercase( ).
Prefer the string concatenation operator in case of to create Strings
at compile-time, when possible.
We need to use StringBuffer to create Strings in runtime.
When size exceeds its size, it has to allocate a new character array
with a larger capacity when it needs; it copies the old contents into
the new array, then it uses to discard the old array.

Example:
package com.rule;
class Specify_StringBuffer_capacity_violation1
{
private StringBuffer sb = new StringBuffer(); //
VIOLATION

public void method(int i)


{
sb.append(i);
}
}

Should be written as:


package com.rule;

class Specify_StringBuffer_capacity_correction1
{
private final int SIZE = 10;
private StringBuffer sb = new StringBuffer(SIZE); //
CORRECTION

public void method(int i)


{
sb.append(i);
}
}
Since now we are comfortable with the code tuning, we will move on
to tuning by tweaking the JVM and improving the garbage collection
capabilities for our application.
Best Practices
These best practices are at the core of performance tuning, and as
such, these should be followed to extract maximum performance
from your application:
1. Keep Java and OS updated: Any new release brings with it
new features as well as better performing and optimized
old features. So, before even contemplating any code
tweaking, it would be best to upgrade to a new version of
Java™. Of course, how easy to say this, but as we know,
there may be applications that cannot be upgraded, due to
a number of reasons. In such cases, we may try to update
the OS, because it may be that Java is platform-
independent, but the truth is that its performance does rely
on the underlying OS.
2. Follow Java coding standards: Although the performance
of an application does rely on the underlying OS, Java
version, etc. It also depends upon how you tune your code
or write your code for the best performance. As such, when
the system has to process a loop lesser number of times or
when an in-built functionality can do the work faster, we
should use the best practices.
Java Code Tuning for Optimum Performance
1. Remove Synchronization Issues: Although synchronization
may be unavoidable in certain programs, it is always better
to measure the performance of such programs and find an
alternative if possible. You may consider re-designing or re-
implementing the part of code to do so.
2. Use Exception handling intelligently: Exception handling in
Java is slow. Use exception handling to handle exceptions
that your application cannot tackle and not handle simple
errors that could be deemed unnecessary.
3. Tune strings for best performance:

a) Create literal strings instead of creating new Objects of


String using one of the constructor methods.
b) To alter a String, use character arrays.
c) To remove, insert, append or replace a character to a
string or to concatenate/split a string, use either
StringBuilder or StringBuffer class.
4. Tune JSPs and Servlets:

a) In a JSP, include the correct “include” - The include


directive is better and faster than the include action
because the page does not get compiled during run-time
and hence does not require any server-side processing—
except the delivery of the page to the client. If your file
does not change often, or if it is not a dynamic page, use
includes a directive to improve performance.
b) Use the correct UseBean action – Utilize the scope
attribute within <jsp:useBean> action tag intelligently to
increase performance. Data Caching using init() – Use
this method for data caching. For example, connection
pooling would be better performed using the init() method.
That is because it is the first method invoked by the server
immediately after servlet-instance is created and before
any client requests are processed.
c) Disable auto-reloading - When an application is
deployed, auto-reloading is very expensive. Auto-
reloading affects performance because it includes the
additional activity of unnecessary loading, which is a
burden on the Classloader. The best option is to keep this
facility OFF in a live/production environment.
d) Sessions or no sessions – It is generally advisable not to
use session tracking explicitly unless it is required. This is
because –

1. Session tracking is expensive. Every time there


is a request, the HTTPSession object is
processed. This would cause performance issues
in case there are any heavy objects stored within
HTTPSession. So avoid storing such heavy
objects.
2. Session tracking for a long time is unnecessarily
expensive. Maintain a low session- timeout value
for best performance.
3. Always close sessions when not required using
the invalidate method. This would reduce the
load on the server and help improve
performance.

e) Compressed data is always better: Utilize gZip to


compress data as it is faster to send data across to the
client.
Memory Management for Optimum Performance
A programmer should ensure sure that an object’s reference has
been made null once the work is done with the object so that it will
be eligible for the garbage collection. It is one of the memory
management techniques.
It is always advisable to delay the memory allocation for an object
until it is not required. This technique results in the usage of this
memory efficient for the required processes and also results in
effective time and memory management.
There are various methods for carrying out Java performance tuning
using memory management techniques – Ergonomics, Garbage
Collection mechanisms, and tweaking various JVM related
parameters.
Ergonomics is the smart tuning technology included within the JVM.
You must know the ergonomics of the JVM to be able to tweak the
heap size and other parameters to optimize performance.
Use a connection pool instead of creating a connection directly
whenever required. If application server is there for the applications,
use the connection pooling facility available for the server by
configuring the properties like initial number of connections to be
created, maximum number of connection and incremental size if the
application needs extra connection after all the initial connections are
in use and maximum number of connections is not yet reached.
It is essential while tuning Java for maximum performance that the
JVM is not only allowed to use the best Garbage collection
algorithm, but also to ensure that the Garbage Collector intentionally
collects any unnecessary objects.
Wrapping up!
Java is the most used programming language nowadays. We can
improve the performance of Java by doing some good practice as a
developer. Give a try to make it as a regular practice in your daily
development process.
Chapter 2: Advanced Strategies for Improving
Java Code Performance

Introduction
This chapter lists out few tips on performance tuning while working
with data, method calls, loop iterations, etc. The primary intention
of creating this chapter is to guide the people who are less
experienced in advanced methods and strategies for best coding
practices.
It has some of the simple and easy to follow tips and best
practices, a developer should learn to code good and portable
code so that it is easier for java coders to understand, develop and
maintain the standalone or web or enterprise applications.
Best Practices to Avoid Common Mistakes while
Coding
1. Before writing a fetch/select query, check whether the data
going to be fetched is already available in the parent
method or service or managed bean. Re-Use of available
data will avoid unnecessary, repeated DB calls.

2. When you need just 2 or 3 column value from a table which


has more than ten columns or so, do not go for 'select *' in
the query.

Similarly, do not fetch the complete entity also in case of the JPA
query. Suppose there are 60 columns, and code needs only 2 of
them, the unnecessary fetch will delay query run time.
3. For a query which is used only to get the count of rows with
some conditions, do not put an order by in it. Getting the
count of rows in any order does not make any difference to
the count, but the performance degrades with an order by
clause.
Suppose a parent method PM calls two child methods CM1 and
CM2.
In CM1, data D1 and D2 are fetched from table T1 and do some
operations with the data.
In CM2, data D3 and D4 are fetched from table T1 (same table
as the other method) and do some operations with the data.
D1, D2, and D3, D4 are used for different purposes. Still, we can
avoid the second DB call if they are fetched together in the first
call itself.
This DB call need not be inside CM1 itself but in a common
method. Then pass the required data only to CM1 and CM2.
This procedure can be done even if the data is fetched from
multiple tables using a single query.
4. Avoid calling Select queries from inside 'for' or 'while' loops.
Instead, pass the parameter arguments as list and get the
result set as list itself. Then use for loop, necessary
collection, DTO List, etc. to manage the list of data.
// For example:
for (Long id : idList) {
sql = "Select col1, col2 from T2 where id = ?";
query = em.createNativeQuery(sql);
query.setParameter(1, id);
// fetch and do some operations
...
}
//The above code can be re-written as:
sql = "Select id, col1, col2 from T2 where id in (:idList)";
query = em.createNativeQuery(sql);
query.setParameter("idList", idList);
List<Object[]> resultList = query.getResultList();
//DTO has variables id, col1 and col2 and their getter and setter
methods.
DataDTO dto = null;
List<DataDTO> dtoList = new ArrayList<DataDTO>()
for (Object[] result : resultList) {
dto = new DataDTO();
//set the values to dto using setter methods
...
//Add to dto List
dtoList.add(dto);
}

5. For some queries, the use of 'OR' can slow down the
performance. Instead, try 'UNION' after splitting the query.
For example:
query = select pr_id from tab1 where sr_number in(:srNumList)
OR id in (select ad_id from tab2 where sr_number in
(:srNumList))
//It can be rewritten as
query = select pr_id from tab1 where sr_number in(:srNumList)
UNION
select pr_id from tab1 where id in (select ad_id from tab2 where
sr_number in (:srNumList)

6. For functionalities where certain calculations or formula is


used, for example, in forecast reports, we can do some
planning on where the formulas can be put.
Suppose, for a report, we have around ten columns whose raw
data need to be fetched from DB, and after some calculations,
they need to be displayed on the screen or exported to excel/pdf
files.
Let the data fetched from database is dd1, dd2, dd3 etc. --->
group (1)
Let the data which are calculated with formulas are df1, df2, df3,
etc. ---> group (2)
Let the final data which are going to be displayed in the report
are dr1, dr2...........dr10. ---> group (3)
Assume:
Group (2) data is common for many further calculations for
deriving group (3).
Some formulas use more than one data at a time.
First, create setter and getter methods in the bean for all these
fields. If required, create different beans based on use.
Below are the precautions we can make in this scenario for
better performance:

Do not put any formulas or logic inside getter methods.


Put the business inside setters only.
Set all the data variables in the DAO/Service method
itself while iterating the ResultList (the result of a DB
query or so).
Do not call setter methods more than once for a report
(Arrange the order of calling setter methods according
to the availability of data).
Avoid any chance of repeating iteration of the lists. Do
all the calculations for one set of data in one go (one
iteration).
If the report has too many fields and incorporating the approach
mentioned above is not practical/increase the complexity of the
method, go for sub-method calls from the loop. In any case,
repeated calculations and looping need to be avoided.

7. Do not declare any variable inside 'for'/'while' loop. We can


save memory if we declare them outside the loop. Declare
them just before the set of code implementation where it is
to be used.
For example:
for (int i = 0; i < 50; i++){
List<ItemDTO> dtoList = new ArrayList<ItemDTO>();
//logic Implementation
}

//The above code can be re-written as


List<ItemDTO> dtoList;
for (int i = 0; i < 50; i++){
dtoList = new ArrayList<ItemDTO>();
// logic Implementation
}

8. When JPA is used, if the entity structure is complex or too


many fields are present, merge operations might take a long
time. In the cases where the fields to be updated are very
few and rows to be updated are more, we can avoid direct
merge operation with the entity.

When it is observed that it is taking a long time than persist


operation, avoid the merge and replace it with a simple native
update query. It will work really faster.
9. In case of maintenance projects, when there is a need to
add additional functionality or screen, people tend to re-use
the existing complex query written for some other purpose,
instead of writing a new simple query. Using JPA, to get any
child table, do not use a query that fetches the whole set of
parent and child records. Simply write a query to fetch that
single entity by passing the id or so.
10.
When working with JDBC to select data from a table,
avoid using select * from and use the required column
names if all the columns are not required, and only some
columns are required as it improves the performance.

Take appropriate care when selecting a JDBC driver. The points


below should be kept in mind.

Use the JDBC-ODBC driver (type 1 driver) only when there


is no driver available for the database. This type 1 drivers
are slower when compared to other drivers as the
conversion of JDBC calls to ODBC calls and ODBC calls to
database-specific calls involves.
Use type 3 driver in three-tier applications (client-proxy
server-database).
Use type 2 driver in two-tier applications (client-database).
Use type 4 driver in applications that need applet and
database communications.
Type 2 drivers are slower when compared to type 3 and
type 4 drivers, but faster when compared to type 1 driver.

11.
For autosuggest/autocomplete (suggestion appearing on
UI screen, based on user input for completing the entry), do
not go for DB query on every input change. Put the whole
data from DB in a master list/map and then compare the
input with the master data list/map. Keep this master
list/map ready, populated with data well before the actual
autosuggest requirement.
12.
Use JDBC’s batch update feature to send multiple queries
to the database. It improves performance and also reduces
the number of JDBC calls to the database.
13.
Cache the data that is static in the database tables. It
reduces database calls and improves performance as once
the data has been fetched and cached, there is no need to hit
the database for that data anymore. There is another type of
data called read mostly data which is not static and data
changes often. This type of data can also be cached by
specifying the refresh time limit so that the data can be
refreshed periodically. Most of the application servers support
the caching feature. The programmer needs to set the values
in properties files or by some other means like XML files etc.s
14.
Ensure that the JDBC connections, statements, and result
sets are closed or released to avoid memory leaks.
15.
For the same data (variable), avoid null and blank checks
everywhere in code it is used (as long as the data is not
updated anywhere in the code). Do these checks once while
the data is fetched or updated by the user/program.

16.
Suppose we require 2 DAO methods for two different
queries (for two different DBs). The input (in clause) of the
second query is the output of the first query, which needs to
be given as a list.
Query1 -> select id, name from db1.testtab where desc = 10;
Gives the output as List<Object[]> result1;
Query2 -> select details1, details2 from db2.testtab where id in
(:idListResult1);
Create the idListResult1 while iterating the result set in the first
DAO method itself. Else we may have to keep a new loop for
creating the list in the service method, which can degrade the
performance.

17.
While comparing any field inside two lists in a loop using
if condition, use break inside a loop if a condition is satisfied
and no more similar result is expected. This will reduce loop
execution time.

18.
While constructing data tables with pagination in
JSP/faces, there may be a need for showing the total
records count. Some people write different queries, one for
getting the total count and another one for fetching the data
for that page.

For the cases where partial fetch is not followed, avoid the
duplicate query. Instead, write the query to fetch the details and
then get the size of the result list and show it as a total record
count.
Consider the scenario below.
In the class SampleClass, there are few public methods and
also private methods method1, method2, CM1, CM2, CM3,
CM4, and refreshScreen.
Assume that you are asked to create new functionality that
would require all these private methods.
//For example:
public class SampleClass {
//public methods here

private method1(){
//variable declaration and logic
CM1();
CM2()
refreshScreen();
}
private method2(){
//variable declaration and logic
CM3();
CM4()
refreshScreen();
}
private CM1(){
//Implementation
}
private CM2(){
//Implementation
}
private CM3(){
//Implementation
}
private CM4(){
//Implementation
}
private refreshScreen(){
//DB calls and other logic
}
} //end of class SampleClass
You need the functionality in methods CM1, CM2, CM3, and
CM4 and finally refreshScreen.
In this case, do not opt new methods as below.
public newMethod1(){
//variable declaration and logi c
method1();
method2();
}
This will repeatedly call the method refreshScreen() and lower
performance.
Hence create the new method as below
public newMethod2(){
//variable declaration and logic
//calling private methods
CM1();
CM2()
CM3();
CM4()
refreshScreen();
}
While altering existing code, do a thorough analysis of each and
every line of code and method call and make sure not to repeat
any DB calls or any method implementation.
Tips for Developing the Java Application Using
MySQL and MULE
1. Use the DSL connection for downloading the JAR files.
2. Add the Folder that contains the Java or Jar or XML files to
the classpath.
Otherwise, you might get the “file not found” error.
3. Add the Log4j.Properties into your Classpath folder if you
wanted to view the debug messages at the console without
writing any System.out messages.
This is useful in debugging the code when you are writing
only the XML file to perform some task.
4. If the MySql database is installed on the different machine
other than the Application server, then please check the
connection from the Standalone remote machine to the MySql
Server. Also, assign the permissions for the remote hosts
(running the Application Server) to connect and query the
database.
Otherwise, you may be able to connect to the MySql
database using the Unix Shell window. But still querying the
database form the client machine Application server will not
be possible.
5. As the plug-ins for the latest Mule versions are not available
now and the Old one is not compatible. So do not use them
for running a MULE project.
Otherwise, you may get FileNotFound or MethodNotFound
exception.
6. In case the variable defined in the Java file is used by the
config.xml file of the MULE. Then do not write the names in
the camel casing. Otherwise, mule parser might not be able
to recognize the variables. We have faced this issue while
inserting it into the database using the MULE-Config.xml file.
7. If the Mule-Config.xml uses the Java beans used in the
project, then do not add any other method except the getter
and setter methods. Otherwise, the run time error will be
thrown by the server.
8. While testing for some FTP and HTTP functionality, please
make sure that your machine has access to that FTP or
HTTP site, as firewalls might block some sites. So, in that
case, you might not be able to fetch the contents of the file.
9. In case if you are using “select MAX(column_name ) from
table_name,” and it is returning null even if the column does
not contain any null value. Then please check whether the
MySQL version you are using is greater than 3.0 since this is
a known bug in MySQL.
Chapter 3: Best Coding Practices for Java
Programming
Introduction
This chapter gives a brief introduction and tips on how to improve the
performance of Java-based applications to write effective Java code.
This helps fresh Java programmers in avoiding common mistakes
related to the program’s performance early in the
projects/applications and also helps experienced developers just to
cross-check the code and rectify the mistakes if any present.
Best Coding Practices
Lazy Initialization
Always prefer lazy initialization by avoiding unnecessary creation of
objects. As object creation is very expensive and it impacts
performance as well, tries to create/initialize an object only when
required say, for example, by having some condition checks like null
or empty.
The following example demonstrates this concept:
String userOperation = null; // Lazy initialization
……..

userOperation = getUserChoice();
if(userOperation.equals(“1”))
// Code to open a new document
else if(userOperation.equals(“2”))
// Code to update the opened document
else (userOperation.equals(“3”))
// Code to delete data in the document
……………..
public String getUserChoice() {
if(userOperation == null) // Condition check for initialization
userOperation = readUserChoice();
return userOperation;
}

Public String readUserChoice() {


System.out.println(“Enter 1 for Open New Document, 2 for
Updating the Opened Document, 3 for Deleting the data from
Document followed by pressing Enter key”);
Scanner scanner = new Scanner(System.in);
userChoice = scanner.nextLine();
return userChoice;
}
Stack Trace Avoidance
Avoid displaying the stack trace to the end-user; instead, display a
generic message to the end-user by keeping in mind that the
message should be understandable to a non-technical end-user. The
actual message can be logged by using any logging API so that the
developers can look into this to understand and fix the problem. Not
only this, the stack track display may lead to a security risk.
The following example demonstrates this concept.
public boolean copyFile(File sourceFile, File destinationFile) throws
CopyingException {
try {
// Code to copy file at source path to destination path
}
catch(IOException ioe) {
throw new CopyingException(“File copy operation failed ”,
ioe);
}
}

public boolean FileOperations {


………….
public boolean shareFileToUser(File sourceFile, User user)
throws SharingException {
try {
return copyFile(sourceFile,
user.getSharedFileDestination(sourceFile));
}
catch (CopyingException copyException) {
throw new ShareException ("Sharing failed due to an
internal error," copyException);
}
}
…………..
}

If the developer simply uses the IOException, there is a chance that


sensitive information like “permission denied” may be exposed to the
end-user. Instead of that, here, a generic message will be shown.
Use Throws Clause Wisely
Be cautious when using the ‘throws’ clause in a method header.
Avoid grouping exceptions that are related in a generic exception
class (Exception). For example, consider that there is a requirement
to read a file in a Java application. To read the file, the file should
exist. If it doesn’t exist, a ‘FileNotFoundException’ exception should
be thrown. If the file exists, the next task is to read that file. If there is
any problem in reading that file, an ‘IOException’ exception should
be thrown. These two are for two different scenarios. If these two
exceptions are grouped into a generic exception class, i.e.,
‘Exception,’ there is a chance that some important or valuable
information is lost.
Use ‘PreparedStatement’ Instead of ‘Statement’ for Database
Operations
This should be done, especially when working on sensitive
operations like checking login credentials to enter into a web site.
Consider the following code snippet:
String username = request.getParameter(“name”);
String userPassword = request.getParameter(“pwd”);
Statement stmt = connection.createStatment(“select department,
address from users where userId = ’”+ username +”’ and password
=’” + userPassword + ”’”;
Consider that the user gives input for user name text field as
testUser’;// ’. Then the query will be as shown below:
select department, address from users where userId = ‘testUser’;//
and password=…
As there is a semicolon after the user name ‘testUser’ in the input
and ‘;’ is treated as the end of a SQL query, and there is a Java
comment after the semicolon, the rest of the query will be ignored by
treating it as a Java comment. If the ‘testUser’ is a valid user in the
database table ‘users’ then the department and address will be
fetched without having the password. So, an unauthorized user can
see confidential data without having the required data. To avoid
these sorts of things, use ‘PreparedStatement’. As the parameters
will be substituted at runtime, there is no chance of these sorts of
things with PreparedStatement.
Not only this, PreparedStatement will be preferred if a query needs
to be executed multiple times. As it’s a precompiled statement, it will
be faster in this kind scenario.
When working with operations on Strings such as inserting,
appending, concatenating, removing, etc., prefer to use StringBuffer
or StringBuilder class. As StringBuilder is non-synchronized, prefer it
over StringBuffer if there is only a single thread performing the
operation(s) as the performance is good with this when compared to
StringBuffer which is a synchronized one and it needs to get locks
and release locks which result in less performance.
Try – Catch- Finally Block
Use try-catch-finally appropriately during the streams and database
operations. When working with database operations using JDBC,
database connections will be opened generally in the ‘try’ block. If
the try block is executed successfully, then catch blocks won’t be
executed. So, the catch block is not the correct place to close the
connections. If the try block is not executed successfully in a
complete manner, then catch block(s) will be executed. So, try block
is also not the correct place to close the connections. The ‘finally’
block will be executed irrespective of whether ‘try’ or ‘catch’ block got
executed. So, close streams and connections in the ‘finally’ block.
Make sure that constant value should come first in the comparisons.
Otherwise, there is a chance that it results in a ‘NullPointerException’
exception. The following code snippet illustrates this:
private static final String CONSTANT_STRING = “test”;
private boolean compareStringWithConstant (String inputString) {
if (inputString.equals (CONSTANT_STRING))
return true;
else
return false;
}
If a ‘null’ value is passed to this method as a parameter when calling,
it results in a ‘NullPointerException’ exception. The following line
causes the exception:
if (inputString.equals (CONSTANT_STRING))
To resolve this problem, make the constant value as the first one in
the comparison like this:
private static final String CONSTANT_STRING = “test”;
private boolean compareStringWithConstant (String inputString) {
if (CONSTANT_STRING.equals (inputString))
return true;
else
return false;
}
Be Cautious when Working with Collections
LinkedList can be used if add/access/remove objects at the
beginning of a collection are required, and thread-safety is not
required.
Synchronized LinkedList can be used if add/access/remove objects
at the beginning of a collection are required, and thread safety is
also required.
Use ArrayList or Vector with proper initialization if
add/access/remove objects at the middle or end of a collection. If
thread safety is not required, use ArrayList; otherwise, use Vector.
Prefer ListIterator over Iterator and Enumeration for iterating a List
type. Both side traversals are possible with this.
Prefer Swing over AWT when Thread Safety is not Required
As Swing is a lightweight framework and platform-independent, it
suits well on any platform. Swing also offers more API than AWT.
Make sure that you never combine the components of AWT and
Swing. Mixing the components may result in display problems.
Swing components generally start with ‘J.’ For example, button in
Swing it is named as JButton whereas it is named as Button in AWT.
Take appropriate care when you need to work with synchronization
in Java applications. Avoid making the complete method and
synchronized and use synchronized blocks by placing the critical
operations in the synchronized block(s). More amount of
synchronizations results in less performance of the application.
Use Binary and Character Streams Instead of Normal Byte by
Byte
Don’t use one byte at a time as the read/write operations will be very
slow with the normal byte-by-byte behavior. To improve the
performance of input/output streams, use binary and character
streams. Binary streams are to handle binary data, and examples
include:

InputStream
OutputStream
BufferedInputStream
BufferedOutputStream
FileInputStream
FileOutputStream
Character streams are to handle character data, and examples
include:
Reader
Writer

FileReader
FileWriter
InputStreamReader
OutputStreamWriter
BufferedReader
BufferedWriter
PrintWriter
Prefer primitive data types than wrapper classes as far as possible
as they are more efficient than wrapper classes. Also, prefer to use
local variables than class variables as accessing local variables is
faster when compared to accessing class variables.
In multi-threaded applications, take appropriate care using w.r.t
objects and class variables. The memory for objects and class
variables will be allocated in the heap which is not thread-safe as
each thread shares the same heap. For methods and local variables,
the memory will be allocated in the stack which is thread-safe as
each thread will have its own stack. So, to avoid concurrent access
related issues in the heap, use synchronization.
Advanced Tips in Java
Here are some advanced tips for developers working on Java. These
tips help the users, especially advanced users to get additional
knowledge in Java.
How to Set the classpath in UNIX for a Particular Session
Classpath is set to locate the class file. We can run the class files
from any working location thereafter if the user wants this
CLASSPATH only for that particular UNIX session. This method is
session-specific.
Syntax: export CLASSPATH=:<Path of the class file>:
Example :
Working location = /extractions/extrtst/GT/
Location of class file = /export/home/ABC
export CLASSPATH=:/export/home/ABC:
In this case, we are using only one class file. We can set the paths of
various class files separated by a delimiter “:”
How to Set the Default classpath in UNIX for any Session
Classpath is set to locate the class file. We can run the class files
from any working location after that. If the user wants the same
classpath every time he/she login, append the syntax below in the
“.profile” file before logging on to the UNIX server. The classpath set
here will be set for every UNIX session. This case is used only if the
class files are very much needed for every session in a default
manner.
Syntax: export CLASSPATH= :<Path of the class file>:
Example:
Working location = /extractions/extrtst/GT/
Location of class file = /export/home/ABC/
Open the “.profile” file in the UNIX server or use the Vi editor to do
the same. Append the command below at the end of the file.
export CLASSPATH=:/export/home/ABC:
In this case, we are using only one class file. We can set the paths of
various class files separated by a delimiter “:.”
How to Compare Strings
Compare only starting part: startsWith function can be used to
compare the first part of the string with already defined or acquired
string. It checks whether the first part of a particular string matches
exactly with other string defined.
Boolean temp = String1.startsWith(String2);
It Results as true if starting the string1 matches with the whole of
string2, which was given as argument or else it will result as false.
Example:
String1 = Starting Extraction Stats
String2 = Starting Extraction
Boolean temp = String1.startsWith(String2);
Result of temp will be true
Compare only ending part: endsWith function can be used to
compare the last part of the string with already defined or acquired
string. It checks whether the last part of a particular string matches
exactly with other string defined.
Boolean temp = String1.endsWith(String2);
It Results as true if ending of the string1 matches with the whole of
string2, which was given as argument or else it will result as false.
Example:
String1 = Ending Extraction Stats of format
String2 = Stats of format
Boolean temp = String1.endsWith(String2);
Result of temp will be true
Get a specific part of the string: If you want to get a specific part of
a string, then you can use the function Substring.
String String2 = String1.substring(begin Index);
For the above syntax, it will return a string trimming the first ten
characters.
Example:
String1 = INFO: File Name
String String2 = String1.substring(5);
Result: String2 will be File Name
You can also use, String String2 = String1.substring(begin index, end
index)
String String2 = String1.substring(1, 5);
Result: String2 will be File Name
How to Check Whether the File Exists or Not from the Input
This is the case we are taking the input from the console (UNIX or
cmd). If you want to check whether the file exists or not and print the
appropriate message and loop for the same.
Example: print the appropriate string for the interaction with the
user
System.out.println ("Enter the Path (with filename): ");
Get the string as shown in the syntax below
BufferedReader Read = new BufferedReader (new
InputStreamReader (System.in));
Read the input as using readLine().
String Filename = Read.readLine();
Then to check whether the file exists or not. Convert the string into
file
File file=new File (Filename);
boolean exists = file.isFile();
The syntax above checks whether the file or path exists and also
checks whether it is a file or not.
You can also use exists function just to check whether the file/path
given exists or not.
boolean exists = file.exists();
It returns false if the path/file does not exist and true if it exists. Then
you can give the appropriate comment for the interaction.
If you want to iterate the loop until the user gives the correct path,
then put a while loop before asking for input with the condition as
true. Then the loop iterates till the user gives the correct path.
Chapter 4: Coding Standards for Programming
Introduction
This chapter defines the coding standards to be followed in a
programming language while writing your code. The naming
conventions, standards, and tips compiled here should be followed.
It takes advantage of the features and facilities available in the Java
language and the Visual Cafe for Java IDE. This disciplined way of
following the convention results in a highly maintainable and easily
readable code.
Naming Conventions
Package Names
Package names should be all in lower case and should be of the
following format. The module, domain, or package names should
uniquely identify the package. The module or domain-specific names
will be like ui, arch, domain, etc… These names are coined after the
services of architecture or use case groups or any other project-
specific grouping.
Class Names
Class names must start with an upper case letter for every word,
with lower case letters for non-initial characters. No leading, trailing
or embedded underscores should be used. Limit the class name
length to a maximum of 30 characters.
Also, the class name should follow the pattern <Meaningful Name>
<Type>. In this pattern, “Meaningful name” identifies the class nature
like Customer, Product, etc. and the “Type” identifies the category of
class. The category is “Exception,” “Screen,” “Controller,” etc.
EJB Class and Interface Names
The classes and interfaces for EJBs should follow the following
conventions in places wherever applicable. The bean name should
follow the same conventions as like class name. If the Enterprise
bean to be created is Xyz, then
the Bean class should be named as XyzBean,
the Home interface should be named as XyzHome and
the Remote interface should be named as Xyz.
For an entity bean, the key class should be named as XyzKey.
For example:
If the bean to be created is Address, then the naming convention is
as follows:
Bean class: AddressBean
Home Interface: AddressHome
Remote Interface: Address
Key class (in case of entity bean): AddressKey
Class Field Names and Variable Names
General
Variable names must start with a lower case letter, but use an upper
case initial letter for every new word. Initial or trailing underscores for
private variables must not be followed. Limit the variable name
length to a maximum of 30 characters.
Example: empAddress, fixedSalary, employeeAge
Arrays
Arrays should always be specified using the form, and the maximum
length of the array name is 30 characters.
<datatype>[][]…[] arrayname;
Example: int[] companyNames;
double[][] salary;

The form given below must NOT be used:


int myArray[]; // Wrong use
Vector and Hashtable
Vector and Hashtable names should end with an‘s’ to represent the
multiplicity of elements as far as possible. The maximum length of
the name should be restricted to 30 characters.
Static Final Variable Names
Static final variable names should be in all capitals, as an indication
that they are definitions. Use underscores to separate words. Limit
the length of the variable name to a maximum of 30 characters
inclusive of underscores, if any used. No leading or trailing
underscores should be used.
Example: INCREMENT
MAXIMUM_LIMIT
Hard-Coded Values
If there is a requirement for “hardcoded” values for a specific
requirement, then declare them as static final variable and use them
in the code. If the value required is for one method only, then declare
that final value within that method itself. This improves the readability
and maintenance of the code.
Example: if (inputUrl = “jdbc:oracle:sample”) { ☐ Wrong Usage
....
} else {
....
}

Expected code is as below :

static final String JDBC_URL = “jdbc:oracle:sample”;

....

if (inputUrl = JDBC_URL) { ☐ Correct Usage


....
} else {
....
}
Method Names
The method name should be chosen so that it conveys the intent of
the method. Method names should start with a verb like do, get, or
move to indicate the functionality. The convention for method names
is the same as the convention for variable names.
Note: If the method is a constructor, the convention to be followed is
the same as the class names.
Example: get MyName ()
do Modification ()
copy Object ()
Arguments Names and Method Arguments
The convention for argument names is the same as the convention
for variable names, and must never use trailing or leading
underscore.
Meaningful names should be coined for arguments. Use the same
name for arguments as for the field value.
Example: doDivision (int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;

}
Code Format
if-else structure
Each block should start in a new line, and the opening brace should
be there in the starting line of the block itself.
Example 1:
if (myName.equals(yourName)) {
ChangeYourName();
System.out.println(“Name Changed Successfully”);
} else {
GoodLuck();
System.out.println(“No Change Required!”);
}
Example 2:
Even if the statement for the action of an if-loop is only one, it should
be enclosed with braces and code formatting, followed as below.
if (yourAge > myAge) {
System.out.println(“You are older than me!”);
}
try-catch-finally
Each block should start in a new line, and the opening brace should
be there in the starting line of the block itself.
Example :
try {
....
} catch (arg0 e0) {
....
} catch (arg1 e1) {
....
} finally {
....
}
Java Source File Style
Copyright Notice
/*
* @(#)Terminator.Java 1.0 10 Jan 2020
*
* The copyright notice must appear here. It must also include
* so that version information is easily searchable using tools
* the above line.
* The copyright text needs to be FINALISED.
*
*/
Modification Log
The modification log must appear immediately after the copyright
notice.
/*
* Modification Log
* ----------------------------------------------------------------------------------
--------------------
* Ver Date Change ID Modified
By Description
* ----------------------------------------------------------------------------------
--------------------
*/
Package and Imports
The package line must be the topmost line in the Java file, before the
copyright notice.
Import lines should follow the copyright notice and mod log. If there
is a reference to more than one class under a directory, then “*”
should be used to represent the classes. If there is only one class
reference, then the exact class name should be referred. The
standard packages are listed before the local packages, all in
alphabetical order.
Class
The class comment should immediately follow the import statements
and should appear as below. This set of comment lines will show up
in the documentation for the package when generated with Javadoc
utility. It is a must to follow this documentation format, as irrespective
of the development kit, the Javadoc document generation is
uniformly followed.
Example:
/**
* The class is used to translate an HTTP request
* to a business event. It accepts the HTTP request
* from the Front Component and translates it in
* to a business event with the help of RequestToEventTranslator
* @author Administrator
* @see any other classes/methods that must be referred
*/
In the above example, the first three lines describe the class. The
comment should give a clear description of the class, but at the
same time, the explanation should be kept short. Also, the code
samples can be provided as sample usage, etc.
Apart from the Javadoc comment, any design and implementation-
specific comments must appear inside the class body in a normal
multi-line comment style.
Example:
/*
* This class follows the Singleton pattern. The constructor will
* be hidden and the getInstance static method will be the only
* method will be exposed.
*/

Class Fields
Every public and protected field declared must be documented. The
documentation comment must appear just above the field for which
the comment is intended. The documentation comment for a private
field is optional. The ordering of the fields will be as specified in
Sun’s guidelines.
Constructors
Constructors must be placed immediately after the class definition.
They should be arranged in order of increasing complexity. For
example, the constructor with less number of arguments should be
placed before a constructor with more number of arguments. No
return type should be specified for a constructor, and it should be
public.
Example:
public class DemoClass {
public DemoClass ( ) {
<Some code>
}
public DemoClass(int inVar, String superStar) {
<Some code>
}
}
Accessor Methods
Accessor methods must start with either get for a read operation or
set for a write operation, followed by the property name. Comments
for the accessor methods are relevant based on whether or not the
class is part of the external interface and the complexity of the
method implementation.
Example:
String getName(); //Getter method to read the property value
void setName(String name); //Setter method for writing to the
property
Other Methods
Other class and instance methods will follow thereafter.
Example:
String getName(); //Getter method to read the property value
void setName(String name); //Setter method for writing to the
property
Documentation for “Javadoc”
Documentation for Class
The first line must be a brief definition of the type, which would show
up in the package summary. After the first sentence, a <p> tag
should be added, and the second line must start in the second line.
From the second line, a more elaborate definition of the class must
be given.
Use the html tags <p> new lines, </p> <code> code samples
</code> and <blockquote> block quotes </blockquote> wherever
appropriate. It is a must to enclose all Java data types and methods
"code" pairs HTML tags. Use the see also tags (@see) wherever
appropriate. This line should start as a new line. The last line of the
comment must be the author’s full name and the company name.
Java Comments
Three types are comments are provided in Java language.
Single Line Comment or InLine Comment
This is the simplest comment in Java, which is marked with two
forward slashes in the beginning. This comment cannot fold into
multiple lines.
Here are some examples:
//this is a Single Line comment. The line below is a Single Line
comment after code

jumper = 10; //jumper jumps as per the number


Block Comment or Multi-Line Comment
In contrast to the above, this comment can span multiple lines. The
start of the comment is marked by a forward slash and then followed
by an asterisk (/* ). The start and end of the comment may be there
in the same line or in different lines.
Here are some examples:
/* The start and end of the multi-line comment is in the same line
*/

/* This comment is a bigger one that spans more than a line.


The usage of this kind of comment is to give an elaborate
description of the program or code piece. While giving a
description, try to limit within three or four lines, else it won’t be
software but a … */
Documentation Comment
The documentation comments are used to generate documentation
using the Javadoc utility provided with Java development kits. The
end delimiter is an asterisk followed by a forward slash (*/ ).
/** This is a documentation comment */
/** This is also a
documentation comment
typed on multiple lines */
Usage of Comments
Comments have to be used liberally, and at the same time,
unnecessary comments should be avoided. Whenever there is a
block of code that is complex to interpret, then it is a must to add a
comment for that block of code.

/* a(i,k) and b(k,j) is multiplied and added to the


corresponding element of the result matrix */ ☐ Useful
Comment
result[i][j] = result[i][j] + amat[i][k] * bmat[k][j];

int iterationCounter; //used as iteration Counter ☐


Unnecessary usage of Comment
Using Single Line Comments
Use single-line comments always. The advantages of using single-
line comments are (a) very simple to add (b) can be nested within a
block comment, and (c) can be used to comment block comment
itself. The example below illustrates the above-said advantages.
(a)
myVariable = “My Name”; // Assign my name to the
variable
yourVariable = “Your Name”; // Assign your name to the
variable
isSameName = doCompare(myVariable, yourVariable); //
Check is both names are same
In case if these lines have to be commented out, it is very simple as
below.
(b)
/*
myVariable = “My Name”; // Assign my name to the
variable
yourVariable = “Your Name”; // Assign your name to the
variable
isSameName = doCompare(myVariable, yourVariable); //
Check is both names are same
*/
If the same commenting was done using block comment, then it will
generate a compiler error. The following code illustrates this.
Wrong Usage
/*
myVariable = “My Name”; /* Assign my name to the
variable */
yourVariable = “Your Name”; /* Assign your name to the
variable */
isSameName = doCompare(myVariable, yourVariable); /*
Check is both names are same */
*/
(c)
/*The following piece of code is used to
validate the input parameters. To explain that, this
multi-line comment is being used */
The above block comment can be nested within a single line
comment, as shown below:
// /*The following piece of code is used to
// validate the input parameters. To explain that this
// multi-line comment is being used */
Using Multi-Line Comments
Whenever the comment that should be added runs through more
than one line and specifically that is meant for elaborating the
context, then Multiline comment should be used. Due to the
descriptive nature of the comment, it is very unpleasant to put // at
the start of every line and also while editing the comment, need
arises to format every time to make it as single line comment if // is
used.
Using Documentation Comments
Documentation comments being a special-purpose feature for
documentation purposes only that should be used appropriately. This
comment should be used in front of every public/protected class,
interface, method, and class/instance variable. Documentation
comment may not be required for a private class, interface, method
or variable since these interfaces are not exposed to the class user.
This documentation commenting allows any user of the code to
generate documentation using the Javadoc utility.
The Javadoc utility picks up all the text inside a documentation
comment and formats that into a paragraph. That is, each
documentation comment becomes one paragraph in the generated
document. While generating the document that will be in the HTML
format all the spacing, line breaks, leading asterisks entered within
the source comment are ignored. If special formatting is required in
the generated HTML document, then HTML tags can be included
appropriately. These tags will be reproduced exactly in the generated
document.
For example, if a documentation comment is entered as below in the
source code,
/**
* This is a sample
* documentation comment
* used to demonstrate the
* formatting policy of Javadoc */
Then in the generated document, these lines will appear as below
with all formatting removed.
This is a sample documentation comment used to demonstrate the
formatting policy of Javadoc.
If the formatting above has to be retained in the generated document
also, then the source comment should look as below embedded with
HTML tags.
/**
* This is a sample <br>
* documentation &nbsp;&nbsp;&nbsp;&nbsp comment <br>
* used to demonstrate the <br>
* used to demonstrate the <br>
* formatting policy of Javadoc */
for which the documentation output will be as below:
This is a sample
documentation comment
used to demonstrate the
formatting policy of Javadoc
If it is required to have the leading asterisk should also appear in the
generated document, the source comment should be done as below.
/**
* *This is a sample <br>
* *documentation &nbsp;&nbsp;&nbsp;&nbsp comment <br>
* *used to demonstrate the <br>
* *formatting policy of Javadoc */
The resulting documentation in the HTML file is as below.
* This is a sample <br>
* documentation &nbsp;&nbsp;&nbsp;&nbsp comment <br>
* used to demonstrate the <br>
* formatting policy of Javadoc
As mentioned earlier Javadoc utility ignores all the leading asterisks,
which are continuous. Similarly the asterisks following the start
delimiter /** is also ignored.
Then the document generated will have only the text MAIN
PROGRAM INITIALISATION.
Note: It is a general practice to highlight the comment inside the
source file, as shown above. Since Javadoc treats the first line as /**
followed by many asterisks (NOT /* followed by asterisks), this box
structure is treated as a documentation comment. This will appear in
the Javadoc output and will be bad user documentation. AVOID
USING “BOX” - ING for multi-line comments.
Chapter 5: Best Design Practices in Java
The following are the best practices that provided tangible benefits
not only during development but during maintenance as well.
Let’s look at the Application Design first.
Application Design
Have a Backend Batch Update for Workflow Tools
Explanation: Many a time, we have cases where-in we provide users
to view data, manipulate the data in a series of steps, and save the
data in the system. This works for a light load of 5-10 iterations per
day. However, when we have a huge amount of data, this can tend
to be cumbersome. Hence, if the requirement entails such a
scenario, it is better to build in the bulk update feature using Ant
Tasks.
Guideline Premise – When to apply this:
In the case of users having to perform:

i. A defined sequence of operations where the


complexity is simple to medium (not exceeding five
steps).
ii. Where the same information can be obtained
equivalently from alternative sources such as excel
or text files.
iii. Where the security audit trail does not mandate
entry through the screen and can be performed via
login id in the data row from alternative sources.
iv. All sanity checks are encoded into the business
layer.

Typical Usage Scenarios:

Bulk updates to the system occurring due to large data


changes.
Onboarding clients to the application.
Data migration process before the go-live.
Example : Mapping data from one source to another and saving the
data. This can be done via UI or batch.
Implement a Batched Database Operation in the Data Access
Layers
Explanation : Data access can either be used for a query for a
single item or for a batched query on multiple items. Refactor the
batch operation into an interface which, when implemented by new
query, automatically allows either single item access or multiple item
access in batches. The advantage of batched access is reduced
transaction log.
Note:

The logic for the batch operation should be abstracted


in a base class.
The batch size should be customizable. E.g., Batch size
may be set for 100 items at one query.
This is applicable for all database operations - select,
update, and insert.
Actual code cannot be given here due to client
restrictions.

Guideline Premise – When to apply this:


Best results noticed in case of data access layer having:

i. A simple to mid-size query not exceeding 40 lines


without join conditions.
ii. Keys in ‘where clause’ that run into hundreds of
values or greater.
iii. The indexes are present for the attribute being
queried upon.

Typical Usage Scenarios:

The logic required for lookup an attribute for a single


entity for user operation via User Interface is similar to
the same lookup operation being used in feed
processing during batch processing.
Investigative tools are written typically take in the single
entity being investigated as input. However, they would
need to follow the same path as the actual process.
Example : A typical example would be to look up names for a given
id from the database. It is advisable to have the same code
customized for:

Ability to lookup single id.


Ability to lookup ‘n’ ids.
Ability to break the ‘m’ ids into at most ‘n’ id’s, query the
result, and look up the names and combine them to give
the final result containing ‘m’ ids and names.

Allow Applications to Display Data on the Screen, Export Data


into Excel, Export Data into Text, Export Data into pdf
Explanation : Once the data is generated on the User Interface, the
requirement would be either of the following:

Read the data from the UI.


Save the data in excel and perform calculations.
Send the data in a standard format (pdf) or structured
(.docx) to external sources.
Save the data as data dump txt files for later analysis.

Guideline Premise – When to apply this:

i. It is advisable for all report generating applications to allow


data to be extracted in various formats.
ii. This should be made part of the framework associated with
saving data.

Typical Usage Scenarios:

Saved data as data dumps can be used for UAT testing


or Regression testing.
Users tend to download data into excels and massage it
to cater to their specific needs by running macros.
Downloading report and sending to external sources in
pdf format.
Example: Personal websites hosting the resume of an individual.
Keep the Scheduler Batch Tasks Independent
Explanation:

Keep related tasks grouped together in one scheduler


batch.
If there are specifically known dependencies, then convert
them to explicit trigger file dependencies rather than tasks
depending on each other. This allows for changes in one
set of tasks to be independent of the other set of tasks.
Focus on the result and not type of processing.

Guideline Premise – When to apply this:

i. When the number of dependencies is relatively small ( <


5 dependencies).
ii. This is especially useful when more than one entity is
waiting for an event to occur.
iii. If dependencies are more, then consider refactoring or
use specified event management.

Typical Usage Scenarios:

Grouping database, Java, I/O feed tasks together in their


own respective groups. If there are dependencies between
groups, they will communicate explicitly via trigger files.
Mostly used in schedulers where a set of dependent jobs
would need to function as a unit.
Example: Dining in a restaurant can be envisaged using this model
as below.

i. Diners place all orders with the waiter. Processing of all


orders ends with the trigger of acceptance of an order.
ii. Once the dishes have arrived, the trigger to serve the
order is given to the waiter.
iii. Upon completion of serving all orders, and with no
further orders, the trigger is to provide the bill to diners.
iv. Diners don’t have dependencies on a particular waiter at
the start. Once a waiter takes order, he becomes the go-
between.
v. Diners don’t have dependencies on individual cook
producing the item they ordered.

Allow Queue Skip Mechanism in Queues


Explanation : Queues allow buffering of messages between the
producer and the consumer when their rate of production and
consumption differ. However, many a time a corrupt data message
might block the queue leading to stagnation. Allow skipping of one, a
group of n-messages, or entire queue to allow fault tolerance and
continuity.
Guideline Premise – When to apply this:

i. Skipping a message would not lead to catastrophic


failure or information loss.
ii. The message can be accounted for (maybe by resend of
a message) or reconciled by other means.

Typical Usage Scenarios :


Message queues have varied usages. Some examples we
have seen are:

The arrival of internal messaging between various parts of


an application.
The arrival of SWIFT messages from exchange to the
company.
The arrival of an application processed data from the grid
computing mechanism.

Example : Arrival of cans in the soda bottling unit. One bad bottle
should not clog the queue.
Coding Design
Use Facade Design Pattern for Co-Existing Flows or For Staged
Releases
Explanation: When replacing an existing process with the optimized
process or new process set decommissioning an older process set,
we would like to have control of the functionality set being released
in a staged manner. One way it could be achieved is:

To propagate the place of bifurcation to a single touchpoint


(or as few touchpoints) as possible and then use the
façade pattern.
An interface will abstract the functionality with a slow
transition from old implementations to new
implementations.
The code can be cleaned up of old code once done.

Guideline Premise – When to apply this:

i. The number of touchpoints should be very limited ( one


or at best a few).
ii. The dependencies on specific implementation should
not exist.
Example: A socket box that connects old and new wiring to the
power source could be a good analogy. Once the new wiring is done,
the connection can be switched. The color coding can be an
interface.
Use Strategy Design Pattern for Alternative Implementations
Explanation: When there are different styles of implementations for
different scenarios, but the process remains the same, we use the
Strategy design pattern.
Guideline Premise – When to apply this:
i. Same interface for different implementations.
ii. Typically useful when we want to introduce optimization in
processing. We can refactor the code to be changed and implement
different strategies to accomplish the task.
Example : Processing the items in a queue is a good example of
using the strategy design pattern.

1. FIFO – First in the queue, First Out of the queue. This is


traditional processing. Processing starts at item 1.
2. LIFO – Last in the queue, First Out of queue. This is the
stack processing. Processing starts at the last item.
3. Priority – Every item in the queue has priority. The
servicing queue is based on priority. Processing starts with
Item with the highest priority.

We can have an application which has a queue and queue handler.


The processing can now be built around a strategy maker who uses
one of the underlying strategies to provide the item to be serviced.
Homogenize Code Base in Java for Non-Java Components
Explanation: In some cases, we would have code in multiple
sources – scripting, Java Code, C++ code, autosys jils (scheduling
logic). Sometimes, the benefits of having code in Java, such as
testing and deploying. In such cases, it is better converting all logic
to be in Java.
Guideline Premise – When to apply this:

i. It would be a simple/medium complexity to write a Java


interface/layer for the items.
ii. The end-users can code in Java.
iii. We should have the ability to translate Java to non-Java
and vice versa.
iv. We should be able to program the dependencies and
intricacies of the syntax.

Example: Writing a Java interface to create autosys jils.


This will allow users to code in Java and have an application to
translate it into Jils. Additionally, if we feed jils to the converter, it
would give Java code corresponding to the jils. Advantages are:

No need to keep separate repositories for JIL and Java


code.
In case we need to generate various flavors like multiple
production instances, QA, and UAT versions, having in
Java allows us to maintain a single copy.
Since it is now converted into Java code, jils are now
testable using JUnit.
The release can be automated using Java tools.

Intern Commonly Used Data for Performance Improvement


Explanation : If the values for a particular entity are immutable, then
it would be efficient to intern the values.
Guideline Premise – When to apply this:

i. When the accessed values are immutable – not required to


be changed.
ii. Need to decrease unwanted memory.
Wrap Command-Line Tools with Extended Error Handling
Explanation: Command-line tools tend to get used with little or not
enough error catching. This leads to silent failures, which become
the bane of maintenance. Having a wrapper for these tools with
enhanced error catching will go a long way in preventing errors from
incorrect error catching.
Guideline Premise – When to apply this:

i. We have standardized tools that had standardized error


messages and codes and can be built upon.
ii. If there is already widespread use of the tool, this would
require effort/money to clean up and standardize the
access via scripts.

Example : Command-line tools such as isql and bcp (query tools in


UNIX for Sybase),
have limited error handling. However, this can’t be enforced during
usage due to which we have silent failures. It is better to enhance
the error detection ability and build wrappers around it so that we
have standardized access with error detection.
Release (Quick Tips)

1. Perform scripted database updates for better co-


ordination and to reduce errors.
2. Implement generic comparison tools for reports for
delimited text and excel based reports.
3. Ant tasks for dependency management and build.
Chapter 6: Best Practices in Java Swing
For creating maintainable, reusable, scalable, robust, and high-quality
software products, some coding best practices must be adopted at the
development stage of the application or product. Java Swing
technology is widely used for GUI application development in Java
platform. This chapter reveals some design and coding best practices
practice that may be used for GUI application development using java
swing.
Application Design Best Practices
Use a flexible layout in your application: Using a layout manager
frees the developer from the burden of manually positioning the
component. Determining the absolute position of a component can be
very cumbersome at times. Moreover using a layout manager ensures
that java takes care of window resizing behavior and look and feel in
different display resolutions.
Never mix lightweight (swing) and heavyweight (AWT)
components within a container: Heavyweight components are
always drawn on light-weight components. The reason lies in the fact
that AWT and Swing use a different way of displaying components on
the screen. One effect of using both AWT and Swing component side
by side. Textbox used in this example is an AWT component, and
Combobox used here is a swing component. The figure shows when
the combo box list is opened, AWT textbox is painted on top of it,
thereby hiding some elements of the Combobox list. This behavior is
totally unexpected.
Avoid low-level events and use semantic events: Examples of low-
level events include mouse and key events, and examples of semantic
events are action events and item events. Using semantic events
rather than low-level events makes the code robust and portable. For
example, listening to action events on buttons is preferable to listening
to mouse events on buttons. In this way, a programmer can ensure
that the button will react in the same way when it is clicked on and
when it is triggered from the keyboard (by putting a focus on it and
pressing the space bar).
Another reason is that some compound components like JComboBox
don’t fire low-level events. It fires semantic events, and its
subcomponent fires low-level events which are look and feel
dependent. In order to avoid look and feel (platform) dependent code,
it is always recommended to listen only to semantic events or
compound components.
Whenever possible, use adapter classes for writing event
listeners: Each of the AWT listener interfaces, which has more than
one method comes with a companion adapter classes which gives an
empty implementation of all methods in the listener interface. Adapter
classes provide a convenient way of writing event listeners. Extending
adapter classes, rather than implementing listener interfaces,
eliminates the burden of writing empty implementations of all other
listener interface methods in which the developer is not interested.
This reduces coding time and the length of the code.
Perform a time-consuming task in a separate worker thread:
Developers should use separate threads for performing time-
consuming operations such as extensive calculations and blocking for
network or disk I/O (loading images) etc. so that GUI does not become
non-responsive. A specially designed class named “SwingWorker” can
be used for this purpose.
Update realized components only from event dispatching thread:
Event dispatching thread is responsible for managing and updating
GUI controls. To avoid the possibility of deadlocks, all GUI controls
should be created, modified, and queried from event dispatching
threads. SwingUtilities class provides two methods – invokeLater() and
invokeLaterAndWait() method to do this task.
Functionality
Prompt for unsaved changes: If the user edits some data in the
screen and clicks on the close button without saving the data, the
system should ask the user whether he wants to save changes.
Provide undo functionality whenever possible: User may make
some mistake while filling an input form and so it is a good
programming practice to provide undo functionality in the system
wherever possible.
GUI must provide warnings to the users for those operations
which can’t be undone: GUI should also alert the users for any
actions that cannot be reverted.
GUI should provide feedback to the users about the status of
their work: GUI should somehow make users aware of what is
happening behind the scene for long-running tasks. For example,
while saving data, GUI should show the message “Saving data…” in
the status bar of the application. Hide or disable GUI elements that
are irrelevant in the current context .
The busy mouse cursor should be shown for long-running tasks:
For long-running tasks, the mouse cursor should change to an
hourglass cursor to indicate that the application is performing some
operation in the background.
The following code shows how to change the cursor to an hourglass
cursor before doing a time consuming operation (e.g. submitting a
screen and saving its content to database) and how to revert to
original cursor after the operation is complete.
try {
panel1.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_C
URSOR));
doSubmit();
} finally {
panel1.setCursor(Cursor.getDefaultCursor());
}
Programming Best Practices
Text and Messages: Font size and colors, messages, texts should not
be hardcoded into the application. They should be taken from
properties files so that they are easily configurable.
Window/Dialog Box: Dialog box should be closed on pressing Esc
key. Unlike the Microsoft Windows environment, swing does not
provide this feature by default. But by adding a little amount of code,
this can be achieved easily. You may refer to the following URL for its
implementation procedure.
In an MDI window, making the desktop pane scrollable whenever
some or all part of a child window is placed outside desktop pane’s
viewable area. In that way, one will not lose the child window when he
accidentally places it outside the parent window. In an MDI window,
make the Window menu available. A windows menu lists all active
child frames and lets users easily switch focus between the child
frames.
TextField: Sufficient width to accommodate the maximum length of
the text. The idea is user should not scroll to view the entire content of
a text field. For large content, use textarea instead of textfield.
On got focus, the existing text should be selected. The following code
shows how to implement this.
(i) Extend JTextField to create EnhancedJTextField.
(ii) Override the processFocusEvent method.

public class EnhancedJTextField extends JTextField {


public EnhancedJTextField() {
super();
}
protected void processFocusEvent( java.awt.event.FocusEvent e
){
super.processFocusEvent( e );
if ( e.getID() == java.awt.event.FocusEvent.FOCUS_GAINED
){
this.selectAll();
}
}
}

(iii) Use this EnhancedJTextField class to create your own


custom text fields.
JTextField jTextField1 = new EnhancedJTextField();
TextArea: Scrollbar should be visible when content does not fit inside
textarea. The java.awt.TextArea internally handles scrolling and
displays scrollbars. JTextArea is different in that it doesn't manage
scrolling, but implements the swing Scrollable interface. This allows it
to be placed inside a JScrollPane if scrolling behavior is desired.
jScrollPane1 = new JScrollPane();
this.getContentPane().add(jScrollPane1);
{
jTextArea1 = new JTextArea();
jScrollPane1.setViewportView(jTextArea1);
}
If the tab is pressed, the focus should be shifted outside.
TextArea (in both AWT and Swing) does not provide this feature by
default. By default, if you put focus on textarea and press Tab, a Tab
character is placed inside the textarea’s text. This behavior may not be
preferable to many users because there is no way to shift focus to the
next component or the previous component using the keyboard. The
following technique can be used to overcome this deficiency.
Extend the JTextArea class to create a custom EnhancedJTextArea,
as shown in the following code.
public class EnhancedJTextArea extends JTextArea {
public EnhancedJTextArea() {
super();
this.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (e.getKeyChar() == java.awt.event.KeyEvent.VK_TAB)
{
e.consume();
if (e.isShiftDown()) {
transferFocusBackward();
}
else {
transferFocus();
}
}
}
});
}
}
Use this EnhancedJTextArea class to create your own custom text
area.
jTextArea1 = new EnhancedJTextArea();
Buttons: Every button should have its associated mnemonics.
Mnemonics are underlined characters in a button’s text. These keys,
when pressed together with the Alt key, activate the button. Ideally,
every focusable component (buttons, textfields, checkboxes, radio
buttons, etc.) should have its associated mnemonics attached to them.
This greatly facilitates keyboard operation. Even for components like
JTextField, which does not have their own text, mnemonics should be
applied to its associated label.
The following code shows how to add mnemonics.
...
{
jButtonCalculate = new JButton();
this.getContentPane().add(jButtonCalculate);
jButtonCalculate.setText("Calculate");

jButtonCalculate.setMnemonic(java.awt.event.KeyEvent.VK_L);
}
{
jLabelAmountUSD = new JLabel();
this.getContentPane().add(jLabelAmountUSD);
jLabelAmountUSD.setText("Amount in USD:");
jLabelAmountUSD.setDisplayedMnemonic('A');
}
{
jTextFieldAmountUSD = new JTextField();
jLabelAmountUSD.setLabelFor(jTextFieldAmountUSD);
this.getContentPane().add(jTextFieldAmountUSD);
}
...
The default button should not have mnemonics.
It should be activated by hitting Enter. Please note pressing Enter will
always activate the default button regardless of which component
currently has the keyboard focus.
To do this, follow the simple steps –
(i) Your main class should implement KeyListener, ContainerListener.
Add the following lines of code in your program.
private void addKeyAndContainerListenerRecursively(Component cp)
{
cp.removeKeyListener(this);
cp.addKeyListener(this);
if (cp instanceof Container) {
Container ct = (Container) cp;
ct.removeContainerListener(this);
ct.addContainerListener(this);
Component[] cps = ct.getComponents();
for (int i = 0; i < cps.length; i++) {
addKeyAndContainerListenerRecursively(cp
s[i]);
}
}
}
private void
removeKeyAndContainerListenerRecursively(Component cp) {
cp.removeKeyListener(this);
if (cp instanceof Container) {
Container ct = (Container) cp;
ct.removeContainerListener(this);
Component[] cps = ct.getComponents();
for (int i = 0; i < cps.length; i++) {
removeKeyAndContainerListenerRecursively(cps[i]);
}
}
}
public void componentAdded(ContainerEvent e) {

addKeyAndContainerListenerRecursively(e.getChild());
}
public void componentRemoved(ContainerEvent e) {

removeKeyAndContainerListenerRecursively(e.getChild());
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ESCAPE) {
performEscapeAction(e);
} else if (code == KeyEvent.VK_ENTER) {
performEnterAction(e);
}
}
public void keyReleased(KeyEvent ke) {
}
public void keyTyped(KeyEvent ke) {
}
void performEnterAction(KeyEvent ke) {
JOptionPane.showMessageDialog(this, "Enter
pressed.");
}
void performEscapeAction(KeyEvent ke) {
setVisible(false);
}
(iv) Modify performEnterAction() and performEscapeAction()
to suit your requirement.
ComboBox: Sufficient width to accommodate the maximum length of
the text. The entire text of all items in a Combobox should be visible.
Autocomplete text as a key is pressed.
Menu: All menu items should be given proper mnemonics and
keyboard accelerators, and there should not be any mnemonic conflict
on a page. Items in contextual menus should also appear in a visible
location. Users often have difficulty knowing whether contextual menus
are available and what is in them. For this reason, the items in
contextual menus should also appear in a visible location. You should
duplicate these items in the menu bar or toolbar of the primary
windows in your application.
Use common mnemonics for common menu titles and items. Common
menu titles and their mnemonics are shown below.
Menu Titles Menu Items
File New, Open, Close, Save, Save As, Page Setup,
Print, Preferences, Exit
Edit Undo, Redo, Cut, Copy, Paste, Find, Find Again,
Select All
Help Contents, Tutorial, Index, Search, About
Application

Show ellipsis (…) in menu items where more user action is required.
Avoid the use of second-level submenus, i.e., you should not put
submenus within submenus. Many people find submenus difficult to
use.
Do not disable a menu even if all items are unavailable. According to
Sun's Java Look and Feel Design Guidelines, if all the items in a menu
are unavailable, the menu should still be available. In this way, users
can still display the menu and view all its inactive items. Similarly, if all
the items in a submenu are currently not available, do not make the
original menu item unavailable.
Painting Guidelines
1. Call repaint() method instead of paint() method. Repaint()
method schedules the paint request in the event dispatching
thread. This ensures that realized components are modified in
a single thread.
2. Wherever possible, call repaint() method with arguments rather
than calling no argument version. In that way, you may repaint
only a particular portion of a component instead of repainting
the entire component.
3. If you create any swing component, override the
paintComponent() method instead of the paint() method. You
sometimes see code that overrides paint() instead of
paintComponent().
4. If you create any new component by extending JComponent,
call super.paintComponent() in the first line paintComponent()
method.
5. Use Double Buffering to improve perceived performance.
Double buffering is a mechanism where any components are
first drawn onto an offscreen image and then copy the image to
an on-screen image. This results in the smooth rendering of the
component.
6. Use anti-aliasing to give a better and smooth look to your
components. You may turn on anti-aliasing for your
components, so that jagged components and fonts look
smoother. To implement anti-aliasing, you need to subclass a
particular swing component and override the paintComponent()
method as follows.
Performance Tips
1. Perform GUI operations in bulk to minimize the events
generated. Suppose that you want to add a few items in a
JComboBox. Then instead of individually adding those items
one by one in a loop, create a vector of all elements and
create a new comboboxmodel form that Vector. Now replace
your old model with a newer one. Every time you add a new
element to the Combobox, events are generated, and
listeners are notified. Total effort is proportional to the
number of events generated multiplied by the number of
listeners. To improve performance, the number of events
generated must be less.
2. When totally replacing the contents of a model, construct a
new one instead of reusing the existing one.
3. Use custom models and renderers to handle large datasets
in JList or JTable. Default models for JList and JTable are
vector-based and not suitable for heavy data operations. In
fact, if you use your own model, you can do many
optimizations.
4. Enable outline dragging mode in JInternalFrame for faster
dragging.
5. Use the Lazy Initialization technique to reduce application
startup time. Defer creation and initialization of components
until they are actually needed. Do not construct components
that are not visible initially at the screen startup time. This
allows the screen to come up faster.
Chapter 7: Best Coding Practices for JavaScript
This chapter provides some useful tips to perk up the performance of
the web application, which uses JavaScript.
Performance Tuning
Often performance is compromised in the journey of delivering the
code for the customer requirement before deadlines. While the
product is delivered as required, customers become discontented if
the performance is appalling. A series of activities is taken at a later
stage to improve the performance of the application. Improving the
performance of the application should not be done as a separate
activity rather be kept in mind while coding. All applications are
distinctive, and so are performance tuning techniques to these
applications having common performance requirements. Few
techniques can be followed to achieve performance improvement.
Caching Scripts
The most common way of improving performance is by caching the
scripts. This is done by writing all the scripts in a separate .js file and
include it in the pages required. In this method, the files included are
cached by the browser and avoids reloading of this file when the
user loads a new page using this file. It also makes our web page
lighter. This also helps your code be understandable and
maintainable. It is the simple way of making changes in one file to
get reflected in all the pages.
For example:
<script language = "JavaScript" src
="/cvisit/js/cmmPopupWindow.js">
</script>
Caching Objects
Caching the objects which are used frequently will improve the
performance. Caching the object and using this is less expensive
when compared to creating new objects every time.
For example: Consider this simple example to print the field name.
<script language = "JavaScript">
for(var i = 0; i < document.FormName.elements.length; i++)
{
document.write("The field name is: " +
document.FormName.elements[i].name");
}
</script>
In the above example, the object document.FormName.elements is
accessed multiple times, forcing the browser to dynamically look it
up twice during each loop. First to see if
i<document.FormName.elements.length and second to access the
field name at the current loop index. If the form has more fields, then
more calls. Excessive calls like this not only slow the browser, they
also take up memory, thereby slowing the system.
Caching the object comes in handy to fix this issue. The way to fix
this is to store a repeatedly accessed object inside a user defined
variable, and use that variable instead of the actual object.
<script language = "JavaScript">
var element = document.FormName.elements;
for(var i = 0; i < element.length; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>
In the above script, document.FormName.elements[] is referenced
only half as many times as before. It goes to the array the second
time, instead of the object.
Lazy Initialization
Lazy initialization in common terms is creating objects only when
they are needed. Initializing many objects in onload can make the
browser noticeably unresponsive for a moment. By this, initializing
everything when the page is loaded is avoided. Thus it takes less
time to load the pages increasing the performance. The other
advantage of this is that the same object is never created twice.
Thus it can be implemented along with caching the object.
Don’t Use Eval
eval function evaluates and/or executes a string of JavaScript code
that is contained in the codestring argument. It is slow and affects
performance at a considerable amount. The best way to improve
performance is to avoid the usage of this function. The functionality
of eval can be achieved alternatively by other code.
Consider the simple example:
<script language="JavaScript"> <script
var x = 10; language="JavaScript">
document.write(eval(x*10)); var x = 10;
} document.write(x*10);
</script> }
</script>

The script without eval() takes less time to execute than the one with
eval().
Pre Calculate Loop’s Length
Determining the length of the loop earlier is another common method
to amplify the performance. This will have a minimal effect per
iteration, in most cases. If the length variable is reused in the body of
the loop, the benefit will be greater. It is very easy to do and doesn't
complicate the code, so we just do it anyway.
Consider the simple example:
<script language = "JavaScript">
var element = document.FormName.elements;
for(var i = 0; i < element.length; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>

This above script can be more efficiently written as:


<script language="JavaScript">
var element = document.FormName.elements;
for(var i=0; var len= element.length;i<len; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>
Limit Processing Inside loops
Just like all the other programming languages, JavaScript’s
performance is diminished by doing so much of activities inside a
loop. Limit the work done inside the loop to the degree that is
possible to improve the performance.
Avoid document.write()
When we use document.write() in a small file, the performance
decline is not evident. For bigger applications that involve a lot of
write operations, it is best practice to avoid document.write() for
content display. Alternatively, use HTML tags for content displays.
The performance variations between these two can be observed
clearly by reloading the pages a few times. Stick to the general rule
of using HTML for content display.
Tuning in String Manipulations
Using performance tuning techniques in String manipulations boosts
the performance exponentially. Some of the simple tips that can be
followed are as follows:
String Literals Concatenation
Concatenations are common operations done on Strings. String
concatenation using literals are much faster than variables. In
browsers like Mozilla, the performance gain is more.
Consider the simple example:
“Welcome” + “to JavaScript World.”
will be faster when compared to:
var msg = “Welcome”;
msg = msg + “to JavaScript World”;

Concatenate Using ‘+’ Instead Of ‘+=.’


It is always a better practice to concatenate using ‘+’ instead of ‘+=.’
It seems like a better option to use += in concatenating and
assigning but silently, this eats up the performance of the application.
Consider the simple example:
var msg1 = “Welcome”;
var msg2 = “to JavaScript World”;
var final = msg1 + msg2;
is faster when compared to:
var msg1 = “Welcome”;
var msg2 = “to JavaScript World”;
var final = msg1;
final += msg1;

Use Local Variables than Global Variables


Local variables are the fastest type of variables. Though global
variables are advised when it is used across several functions in the
file, this hinders the performance. The cost of looking up a local
variable is lesser when compared to the global variable. When a
local variable is used to store the global object chain, the
performance is even more improved.
Eliminate Unnecessary Variables
Usually, the variables which will be used only once in the script are
eliminated.
For example:
function fnUpdateVal(newVal) {
var form = document.forms[0];
var newValuew = form.elements[“update”];
newValue.value = newVal;
}

Should be changed to:


function fnUpdateVal(newVal) {
document.forms[0].elements[“update”].value = newVal;
}
Declare and Assign a Variable in a Single
Statement
Declaring all the variables at the top of the function and assigning it
later is the traditional methodology which has been followed widely.
This reduces code clarity and hence bad practice. But declaring and
assigning a variable in the same statement offers a slight
performance boost. This is because the variable is referenced only
once.
For example:
<script language = "JavaScript">
var element, i, len;

element = document.FormName.elements;
for(i = 0; len = element.length; i < len; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>

Should be changed to:


<script language = "JavaScript">
var element = document.FormName.elements;
for(var i = 0; var len = element.length; i < len; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>
Debugging Strategies for Javascript
JavaScript is one of the coolest web tools around. An extension to
Hypertext Markup Language (HTML), JavaScript enables you to
access and manipulate all the components that make up a Web
page.
This section describes some of the mistakes that a JavaScript
programmer does and how to find and rectify it using debugging.
JavaScript – Reads only code, not the mind: In general, if the
JavaScript code is not working in a way you designed, then there is
a bug. Sometimes the design will be perfect and still you encounter
some problems. As we all know, JavaScript never throws straight
forward error.
For Example: If the user clicks on Next button ->
If the action selected from the UI is an addition, then the action to be
performed in addition.
Else the action to be performed is subtraction.
It’s always advisable to write a pseudo code of your requirements so
that even when your script design is perfect, if you face any issues,
this will help you to debug your problem easily.
Bug Isolation: If you try to zero it on a genuine error that is which
lines of code are affected, then the following ways might be useful.

1. Error on page loads? Then the problem might be either


HTML related or in the onLoad event of your code.
2. Error on while giving input to text fields? Then check onBlur
or onChange event.
3. Error on button click. Then check the onClick event.
4. Error on the page closes? Check onUnLoad event.
Documentation: It is always advisable to refer to the
documentation. As I mentioned in my previous section, refer
documentation from Netscape for script related bugs or issues. You
can either download it on your browser or bookmark it for your
reference.
“alert” tracking: If you wrote some 50 lines of script and you face
any issues after running the script, the one easiest way to debug is
to use “alert” statements.
For example, you are iterating a string value in an array. Check
whether the string value is coming as expected in the following way.

1. var strXXX = some value.


2. alert(strXXX);
3. Iterate it.
In this way, you can track the issue step by step to rectify it.
Code break up: By breaking a large block of statements into smaller
functions, we can avoid error possibility. This will increase our ability
to code reuse, and our frustration level will decrease.
Elimination: By eliminating the unwanted tracks in finding errors, we
can avoid wasting time and the solution will become more reliable.
This can be achieved by writing several test cases against your
script.
Browser problems: There may be problems because of your
browser too. JavaScript may be disabled in your browser, or your
browser’s version is incompatible with JavaScript. Solving these
issues will help to solve the error.
Checking Script: There may be mistakes happens while writing
your script. This may be keyword error, error in assigning a value to
the variable, parameter passing, etc. Tracking for these problems
may help you solve the issue.
JavaScript Useful Strategies and Methods
We have included various JavaScript methods that are very useful
and easy to implement. Most of the code snippets can be reused as
such. Some of them might require some minor changes.
To check all the checkbox in a page when the select-all
checkbox is checked or to uncheck all the checkboxs in a page
when the select-all checkbox is unchecked .
On click of the select-all checkbox, call the checkAll function. If the
select-all checkbox is checked, checkAll function will call the
selectAll function else checkAll function will call deselectAll function.
The checkAll function will check all the other checkboxes. The
decheckAll function will uncheck all the other checkboxes.
// to check whether the select-all checkbox is checked or not
// call this function when the select-all checkbox is clicked
function checkAll() {
var check = document.getElementsByName("chkAll");
if(check[0].checked == true){
selectAll(check);
}
else {
deSelectAll(check);
}
}
// to select all the check-boxes
function selectAll(check){
var check2 = document.getElementsByName("chkItem");
for (var i = 0; i < check2.length; i++) {
check2[i].checked = true;
}
}

// to de-select all the check-boxes


function deSelectAll(check){
var check2 = document.getElementsByName("chkItem");
for (var i = 0; i < check2.length; i++) {
check2[i].checked = false;
}
}
- chkAll is the name of the select-all checkbox
- chkItem is the name of the other checkboxes
To check the select-all checkbox on a page when all other
checkboxes on the page is checked or to uncheck the select all
checkbox on a page when any of the other checkboxes are
unchecked.
On click of any of the checkboxes other than the select-all checkbox
call the function checkFunction. This function checks if all the other
checkboxes with name chkItem are checked or not. If all the
checkboxes with name chkItem are checked, the select-all is
checked. If any of the checkboxes with name chkItem is unchecked,
then the select-all checkbox will be unchecked.
// call this function when the any of the checkbox other than the
selectall checkbox is clicked.
function checkFunction(){
var count =0;
var check = document.getElementsByName("chkAll");
var innerCheck =
document.getElementsByName("chkItem");
for (var i = 0; i < innerCheck.length; i++) {
if(innerCheck[i].checked == true){
count = count +1;
}
}
if (count == innerCheck.length){
for (var i = 0; i < check.length; i++) {
check[i].checked = true;
}
}
for (var i = 0; i < check.length; i++) {
if(check[i].checked == true){
for (var j = 0; j < innerCheck.length; j++) {
if(innerCheck[j].checked == false){
check[i].checked = false;
}
}
}
}
}
- chkAll is the name of the select all checkbox
- chkItem is the name of the other checkboxes
To get the final count of the selected items across pages in
pagination and validate in JavaScript before form submission.
var finalCount = session.length; //count of items already in
session
for(var i = 0; i < pageList.length; i++){
var currentPageItem = pageList[i];
//checked length is 0 and session length is 0
if (checked.length == 0 && session.length > 0){
// No items checked; previously checked items are removed
for (var l = 0; l < session.length; l++){
if(session[l] == currentPageItem){
finalCount --;
}
} // end for
}
//checked length greater than 0 and session length is 0
else if(checked.length > 0 && session.length == 0){
// No items in session
for(var k = 0; k < checked.length; k++){
if(currentPageItem == checked[k]) {
// checked items in current page
finalCount ++;
}
} // end for
}
//checked length greater than 0 and session length greater
than 0
else {
if(isPresent(currentPageItem, checked)){
// Item is checked
if(!isPresent(currentPageItem, session)){
// Item is not in session; add item
finalCount ++;
}
}
else {
//Item is not checked
if(isPresent(currentPageItem, session)){
// Item in session; remove item
finalCount --;
}
}
} // end main if
} // end for loop

alert (finalCount);
Before using the script, get the three arrays used in the script.
Arrays used in the JavaScript:

session - an array of selected items already in session


(items checked in the previous pages). This can be passed
as a string separated by a comma to the script and then
put into the array.
checked - an array of checked items on the current page.
pageList - an array of all items on the current page, both
checked and unchecked.
The finalCount gives the total count of selected items across pages.
The function isPresent is called to check if an item is present in the
array. The function will return true if the item is present in the array
else it will return false.
//function isPresent(key, Array)
//returns true if key is present in the Array
function isPresent(item, itemList){
var flag = new Boolean();
flag = false;
for(var i = 0; i < itemList.length; i++){
if(itemList[i] == item){
flag = true;
}
}
return flag;
}
To trim leading and trailing spaces from a string in JavaScript
//To trim leading or trailing spaces
function trimString (str) {
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
The thing to note here is that the first .replace actually removes the
leading blank spaces, whereas the second replace removes the
trailing blank space. The first parameter in the .replace is known as a
regular expression.

^ indicates the beginning of the string. Using a ^


metacharacter requires that the match starts at the
beginning.
$ indicates the end of the string. Using a $ metacharacter
requires that the match ended at the end of the string.
\s represents any single space character.
/g represents the global search for all occurrences of the
pattern.
To refresh the parent window by clicking the button in a popup
opened from the parent window. Different parent windows can
create the same popup. When clicking the button in the popup,
the corresponding parent window should be refreshed.
The refresh function should be in the corresponding parent windows
JavaScript. Instead of var i = “/ShowInbox.do”; give the path of the
corresponding parent window. Return 0 if the parent window need
not be refreshed.
// for parent page refresh after clicking ok in a popup
// this function should be in the corresponding parent windows script
function refresh(){
var i = "/ShowInbox.do";
return i;
}
Call the confirm function on the clicking of the button in the popup.
This, in turn, calls the corresponding parent window refresh function.
The refresh function returns the path of the parent window. If the
return is 0, the parent window is not refreshed and the popup
window is closed. If a path is returned, the parent window is
refreshed with the corresponding path and the popup window is
closed.
//for reload of the opener of the confirmation
// this function should be in the pop-up’s JavaScript
function confirm() {
var contextPath =
document.getElementById("context").value;
var i = window.opener.refresh();
if (i == 0){
window.close();
}
else{
window.opener.document.forms[0].action = contextPath + i;
window.opener.document.forms[0].submit();
window.close();
}
}
To disable the corresponding menu bar link and make it bold
upon loading the page.
Consider an application with three pages. There is a link for each
page in the common menu bar. On loading the page, the
corresponding page’s menu bar should be disabled and bold.
In the common menu bar, give an id for each link. Let the id be
menu1, menu2, and menu3 for the corresponding links.
For example, In the common JSP
<div>
<span id ="menu1">
<html:link action="/ShowMenu1.do"> Menu1 </html:link> </span>
</div>
<div>
<span id ="menu2">
<html:link action="/ ShowMenu2.do"> Menu2 </html:link> </span>
</div>
<div>
<span id ="menu3">
<html:link action="/ ShowMenu3.do"> Menu3 </html:link> </span>
</div>
Use the below script in the first page JSP
<script type = "text/javascript">
document.getElementById('menu1').innerHTML =
'<a> <b> Menu1 </b> </a>';
</script>
On loading the first page the link Menu1 becomes disabled and bold.
To make tabs that expand and collapse on clicking.
Tabs that expand or collapse on clicking are very useful and
attractive from a user perspective. The idea behind this is that the
user needs to see only those things which are relevant to him.
See the below code
function newFunction(id){
if(document.getElementById(n).style.display == "none"){
document.getElementById(n).style.display="";
}else if(document.getElementById(n).style.display == ""){
document.getElementById(n).style.display = "none";
}
}
The whole trick is to set an id to the div (or table), and this id is
passed as the parameter to the function. To make the div hidden we
set style.display to none. On clicking the tab the above function is
called. If it is hidden, it is made visible by setting the display to “”. A
common practice is to set the display to ‘block’. But this may lead to
problems because the block is container specific. In Mozilla, it may
affect the whole layout.
One more way to make the div visible or hidden is by adjusting the
height of the div. See the code below.
function showHideSects() {
if (!document.getElementsByTagName) return false;
var headings = document.getElementsByTagName("h2");
for (var i = 0; i < headings.length; i++) {
headings[i].parentNode.className += " open";
/*headings[i].parentNode.style.height = "3em";
headings[i].parentNode.style.overflow = "hidden";*/
headings[i].onmouseover = function() {
this.style.cursor = "pointer";
}
}
Here the tag with name =h2 is made to disappear. The height is set
to ‘3em’.To display the whole content, we set the height to “.” But I
would advise you to stick to the earlier method because it is easy to
understand and reuse.
To ensure than a selected item in a dropdown does not appear
in other dropdowns.
Consider a series of the dropdown. We need to ensure that the
selection in any of the dropdown does not come in the other
dropdowns. Call the function onRowChange on change of the
dropdown
function onRowChange(rowId) {
for(var i = 0; i < getMaxEditableRows(); i++) {
if(rowId == i)
continue;
var rowName = 'optAttr' + i;
var tempVal =
document.getElementById(rowName).value;
document.getElementById(rowName).options.length = 0;
document.getElementById(rowName).options[0] = new
Option("--Select--",'');
for(var j = 0; j < (allAttributesKeyArray.length); j++){
var text = allAttributesKeyArray[j];
if(isSelectedInOthers(text, i))
continue;
document.getElementById(rowName).options[1 +
count++] = new Option(text, text);
}
document.getElementById(rowName).value = tempVal;
}
}
getMaxEditableRows is the number of dropdowns
allAttributesKeyArray is an array of all items in dropdown
// checks whether the attribute is selected in other dropdowns or not
function isSelectedInOthers(text,rowId) {
for(var i = 0; i < getMaxEditableRows(); i++) {
var rowName = 'optAttr' + i;
if(rowId == i)
continue;
if(document.getElementById(rowName) .value == text) {
return true;
}
}
return false;
}
The function is called on onChange of the dropdowns. The
parameter rowId denotes which row was selected, i.e., which
dropdown. The value selected in the dropdown is stored in a
temporary variable – tempVal, after this the values in the dropdown
are flushed by setting its length to zero. Again the dropdown is re-
loaded with values from the allAttributesKeyArray. Before the actual
setting, another function isSelectedInOthers is called. The parameter
‘text’ denotes any value in the allAttributesKeyArray which will be
compared with the values already selected. This function ensures
that the value selected is not selected in other dropdowns. It returns
true or false depending on this criterion. Based on what the
isSelectedInOthers function returns, the dropdown is populated with
values other than one’s selected.
Logout in case of Mozilla
Simply window.close(); will not close the main window in Mozzilla.
Only if it is a child window, window.close(); will work in Mozilla. So to
logout (close the window) in Mozilla, call the below function.
// logout
function closeWindow() {
window.open('','_parent','');
window.close();
}
To validate all Textboxes in the Screen for the following:
i) No fields can be empty
ii) Numeric Validation
i) No fields can be empty
To Validate All the Text Box in the screen so that none can be empty
function validateBlankFields() {
var the_inputs =
document.getElementsByTagName("input");
var validationStat = true;
var flag = 1;
for(var n = 0; n < the_inputs.length; n++){
if(the_inputs[n].type == "text"){
var name = the_inputs[n].name.substr(8);
name = trimString(name);
var values = the_inputs[n].value;
values = trimString (values);
if ( values !=''){
validationStat = true;
}
else{
alert( "All fields must be completed.");
var name1 = the_inputs[n].name;
validationStat = false;
break;
}
}
}
return validationStat;
}
Let us analyze the code line by line.
var the_inputs = document.getElementsByTagName("input");
Here we are getting all the ‘Input’ tags.
for(var n = 0; n < the_inputs.length; n++){
if(the_inputs[n].type == "text"){
var name = the_inputs[n].name;
name = trimString(name);
var values = the_inputs[n].value;
values = trimString (values);
if ( values !=''){
validationStat = true;
}
Next, we are checking all the input tags whose type is ‘Text.’ Then
we are getting the names and values of the ‘Textbox.’ The trimstring
is the trim function mentioned above. After that, we will check
whether the value is a null string. If it is not, we will set the flag to
true.
else{
alert( "All fields must be specified.");
validationStat = false;
break;
}
}
}
This is for giving an alert in case it is null. If it is null, we are setting
the flag to false and breaking from the for loop.
Numeric Validation
Here we are passing the value of the textbox as a parameter to the
function. The for loop iterates through the whole length. We are
storing each character of the string and checking it against a set of
predefined characters. I think the rest is self-explanatory.
This method has its own drawbacks. The main thing is if you enter a
value like ---3…2344, it still returns true because all digits are
present in the above validation. This can be solved if we give a
check on the count and position of “-“ and. “” in the function.
Chapter 8: Best Practices for JavaScript and
ExtJS
Here we have provided the best practices that were captured during
the development of applications on advanced JavaScript, which has
proved to improve the usability, availability, and maintenance of the
application. The learning covers superficially on a wide range of
topics— from naming files and variables all the way to coding
JavaScript that performs well in typical environments.
Organized-structured source code and conventions make code
readable and can provide ease of communication of complex
algorithms.
Project Organization
The project is organized, roughly, into the same structure as a typical
ASP.NET project where the separation is based on stable library
contents and dynamically changing contents – created by
developers, with additional directories called application and
resources, organized as:
application/
css/
images/
js/
resources/
extjs/
css/
images/
js/
The idea is that the application directory is changed frequently, and
the resources directory is relatively stable: it is only updated when
we adopt a new version of a major upstream library, such as ExtJs
itself. This means that most of the time, the resources directory need
not be touched when deploying a new version of the application. If
the application is engineered well, this has positive implications for
performance.
Naming Conventions
The naming conventions were based on what the ExtJs authors
define or what the official stance is from Sencha (owners of the
ExtJs framework).

Files should be named after the primary object contained


within, and each source file should contain one primary
object; for example, the object MyCompany.pkg.Foo
should be contained in the file pkg/Foo.js. Rationale: When
a developer is searching for the source code of an object,
naming the file after that object makes it easy to find.
Constructors (that is, JavaScript “classes”) should be
named with CamelCase names and should be placed
inside a reasonable namespace, declared with the Ext.ns()
function. Rationale: Camel-case names are found in the
majority of existing JavaScript code, and so are consistent
with what most web developers will read, and namespaces
help prevent accidental name collisions.
Variables and functions should use camelCase names with
an initial lower-case letter. Rationale: Again, this is
consistent with the vast existing base of JavaScript code.
For example:
// source file: myproject/MyClass.js
Ext.ns('MyCompany.myproject');// not applicable beyond ExtJs3.0
MyCompany.myproject.MyClass = Ext.extend(Ext.Observable, {
myMethod: function(myParameter) {
// ...
}
});
// for ExtJs 4.0 and above
Ext.define('MyCompany.myproject.MyClass’,{//members…},
{//onClassCreated…}
});
Code Style Conventions
Automatic formatting in newer versions of Microsoft Visual Studio will
mostly follow these guidelines, below are a few highlights:

An opening curly brace goes at the end of a line and has


one space before it; a closing curly brace goes on its
own line and is indented to the same level as the line
that contains the corresponding opening brace.
One space goes on each side of math operators and
equality operators. One space goes on (only) the right
side of other operators like colon, comma, and
semicolon.
Control constructs like “if,” “while,” and “for” should have
one space between the keyword and the following
parenthesis. The “else” keyword should appear one
space to the right of the previous closing brace.
A common belief is that only block statements should
follow control constructs like “if” and “while;” that is, curly
braces should be mandatory for control constructs even
if they only encompass a single statement. A difference
in opinion exists on the same.

If a statement doesn’t fit on a single line, break the line


after a comma, an opening parenthesis, or another
operator. This avoids accidentally invoking JavaScript’s
semicolon insertion misfeature.
Some of these guidelines are demonstrated in an example:
function MyCompany.mypkg.makeCounter(msg) {
var count = 1;
return function() {
var s = '';
if (typeof msg !== 'undefined') {
s += msg + ': ';
} else {
s += 'count: ';
}
return s + (count++) ;
};
}
//example of JavaScript semicolon insertion misfeature
function MyCompany.mypkg.makeCounter(msg) {
var count = 1;
return function() {
var s = '';
if (typeof msg !== 'undefined') {
s += msg + ': ';
} else {
s += 'count: ';
}
return “ the return for the function makeCounter is ”;
s + (count++);
};
}
Development Guidelines
The following are some broad guidelines for writing JavaScript code
that is understandable and performs well based on the application
developed.

Introduce variables at the top of a function . There is no


such thing as block scope in JavaScript like there is in C and
its descendants. Rather, only functions have a scope. So,
introducing variables within a block statement other than a
function—while perfectly legal—is potentially confusing.
Introduce all the variables used in a function at its top.
var f = function() {
var x = 1;
if (x) {
var x = 2; }
alert(x); // output, x === 2
};

An opening curly brace belongs at the end of a line, not


on its own line . Because of JavaScript’s semicolon insertion
misfeature, code that breaks this rule can have very
surprising results:
var test = function() {
return
{
name: 'value'
};
};
var obj = test();
// obj.name is undefined: a ';' is inserted in the line 2

Never use implied global variables . If a variable is used


without a corresponding “var” statement, then the variable
ends up implicitly in the global object (the “window” object in
browsers), which is a source of namespace pollution. If there
is a need to put something in the global object—and almost
certainly it never is—then it should be done explicitly.
Use strict equality operators whenever possible . The
“===” operator is like “==,” except that the latter is non-strict:
it can coerce the types of one or more of its operands. The
case with “!==” and “!=” is similar. Use the strict operators
“===” and “!==” whenever possible, since they perform better
and are less likely to lead to surprises or mask errors. The
non-strict equality operator is not even an equivalence
relation, in the mathematical sense:
// An example of non-transitivity of the ‘==’ operator:
false == 'false' // true
0 == false // true
0 == 'false' // false

Avoid serious arithmetic. JavaScript has exactly one


numeric type, namely the IEEE 754 double-precision floating-
point number. Being a binary storage type, this can have ugly
implications; for example, “0.1 + 0.2 === 0.3” is false. For that
reason, non-trivial arithmetic should usually be pushed up to
a more suitable platform via AJAX.
Always use the second argument to parseInt(). In the
absence of a specific radix, parseInt() behaves like a
programming language, which is probably not what users
want. For example, parseInt('011') is 9, but parseInt('011', 10)
is 11.
ExtJS Development Tips
This section describes some tips for working with the ExtJS
JavaScript framework and producing readable code, is maintainable,
and works well across different runtime platforms.
Prefer ExtJS mapping constructs to simple loops: The functions
Ext.each() and Ext.iterate() are great for acting on each member of
an array or other objects; using these produce shorter and more
robust code than rolling one’s own for loops. Use the former if you
know the object being looped over is an array; otherwise, use the
latter. In the Tailored Workstation project, we created a function
Ext.ux.map()—also aliased to Ext.ux.collect() to make Ruby users
feel at home—that acts like Ext.each() but also collects an array of
results.
// Instead of...
for (var i = 0; i < this.items.length; ++i) {
this.add(this.items.length);
}

// Prefer...
Ext.each(this.items, this.add, this);
Avoid global IDs (that is, avoid the “id” configuration property):
Using global DOM IDs—which is a consequence of using the id
configuration property when creating ExtJS components—is the
moral equivalent of using global variables in a program. That is, it is
sometimes necessary and reasonable, but it should be done
sparingly and viewed as suspicious. In particular, using a global ID
means that only one instance of your component can appear in the
DOM at once, and that may harm developers trying to re-use your
component. Instead of searching for a component by its global ID,
consider (a) using events to communicate among components (see
below) or (b) keeping a reference to the component when it is
created. Alternatively, you can use the itemId configuration property
for child components, which need not be globally unique.
Use events for communication among components: The proper
way to communicate between two unrelated components is to use
the event system. This is a good replacement for the more brute-
force solution of one component looking up another by ID at some
crucial moment. Instead, have one component register one or more
custom events that represent its workflow, and other components
can listen for those events and react to them.
MyCompany.MyComponent = Ext.extend(Ext.Panel, {
constructor: function(config) {
var M = MyCompany.MyComponent;
M.superclass.constructor.call(this, config);
this.addEvents('myevent');
// Now, other components can listen for
// ‘myevent’ like any other event.
},

someMethod: function() {
this.fireEvent('myevent', /*...*/);
}
});
Whenever possible, load data when a component renders: It is
polite when loading data to display a “load mask,” but displaying a
loading mask in ExtJs requires a DOM element, which is first
available after the component fires its render event. So, when you
must load data, the easiest idiom is something like this:
this.add({
// ...
listeners: {
render: function(comp) {
var s = new MyStore();
new Ext.LoadMask(comp.el, {
removeMask: true,
store: s
});
s.load(/* ... */);
}
}
});
Never over-nest the components: A ExtJs grid can act as both a
panel and a container and can have headers too. Hence a grid can
be used when a container and a panel is required
Put validations at the component level: A validation event on
component change event where all the business validation lies and
on submit or save the validation function on panel instead of
individual input controls (text fields and combo boxes) inside the
panel is executed, this function should return true or false based on
its sub-component validations. This will make sure that all the
validation business logic lies in one place, which is easier to maintain
and understand.
Exercise care when two components access the same data store.
Enabling Re-Use in ExtJS
Use inheritance when adding behavior to one type of ExtJS
object. When you are enhancing the behavior of one type of ExtJS
object (for example, a Panel), use inheritance with Ext.extend(). The
example above shows how to create an object that extends
Ext.Panel and add a custom event and method to that object.
When using inheritance, use property defaults and/or override
initComponent(); override constructor() if must. Overriding the
constructor() method of an ExtJs component is tricky because the
contract of that method is tricky; preserve any reasonable
configuration object that exists and add additional behaviors without
colliding with those configurations. The example below adds some
default behaviors to a new type of panel without overriding the
constructor() method.
MyCompany.MyComponent = Ext.extend(Ext.Panel, {
fbar: [],
defaults: {
cls: 'my-css-class'
},

initComponent: function() {
var M = MyCompany.MyComponent;
M.superclass.initComponent.call(this);
// Add some extra components…
}
});
Use a custom plugin when adding lightweight behaviors, especially
to different types of ExtJs objects.
Styling
Avoid inline style attributes: Using the style attribute in markup—
or, equivalently, using the style configuration property on many
ExtJs components—should be done sparingly. Just as CSS classes
and IDs are used to split up semantics from the presentation, so it
should be with JavaScript code and presentation. Prefer using CSS
classes, perhaps via the cls configuration property.
Use selectors to restrict style application to your own
components: In a large project, it is important to make certain that
your CSS changes do not accidentally pollute all areas of the
application. To that end, consider using selectors—in particular,
descendant selectors—to prevent your CSS changes from
“escaping” their intended place.
/* Dangerous... */
.x-panel {
color: #ccc;
}

/* Safer... */
.my-window .x-panel {
color: #ccc;
}
Performance Tips
Place frequently used object chains into the local scope: If there
are many places in a single function that uses
this.a.long.object.chain, use a local variable to lift that constant into
the local scope. Newer JavaScript runtimes with just-in-time
compilers will automatically apply this optimization in the frequently
used code, but many in prominent use —notably Internet Explorer
before version 9 and Firefox before version 3.6—do not.
Minimize the number of HTTP requests: While developing an
application, probably JavaScript code will be placed into many
source files. For the second release of an application, we had more
than 130 script elements, each pointing to a single JavaScript file.
Concatenating those into a single file and a single script element
improved initial page load times by over 30%.
Minify and/or compress JavaScript and CSS files: Applying a
minification algorithm to JavaScript and/or CSS files greatly reduces
the number of bytes that need to travel over the network. Configuring
your webserver to apply gzip or another compression content-
transfer-encoding algorithm to JavaScript and CSS is usually
another significant boost to network throughput, as those tend to be
very low-entropy, even after minification. In one of the projects, we
created a script to minify JavaScript automatically with the Google
Closure Compiler and produce a single file out of our many human-
readable source files; even without gzip, that improved the initial
page load performance by 50% to 80% over a fast network. The
difference is larger over the Internet.
Consider cache correctness: Minification and compression
improve a user’s empty cache experience. Improving the user’s full
cache experience is far trickier but provides another big boost in
perceived performance. Explaining HTTP caching is beyond the
scope of this document, but the steps are (a) ensure that objects that
can be cached such as JavaScript, CSS, and images have different
URLs with each version released, and (b) configure your webserver
to set the cache lifetime of those objects to a very long time. For this
application, Optimize Website Accelerator was adopted, which does
both tasks transparently for IIS.
Caution: Usual practice is to add the script elements, images and
CSS files to the default or initial load page, this can lead to
performance bottleneck as the application will try and download all
the files, particularly if the application performs any task during
load(other than say validation).
Use “EnableSession = true,” while defining a web method, with
discretion as it renders AJAX calls as synchronous rather than in an
asynchronous mode.
Use “JSON( JavaScript Object Notation)” return type rather than
XML wherever possible as JSON is text-based, lightweight, and very
easy to parse.
Useful Tips and Techniques for HTML/JavaScript
Developers
JavaScript is used to implement client-side validation to avoid an
invalid input character. JavaScript is a very useful programming
language, and it is of great help to improve user experience in the
B/C applications. JavaScript has many useful events available to
developers.
Here are some of them:
onKeyDown event : This JavaScript event is invoked whenever the
user key of the keyboard is up. Commonly we use this event when
we want to run some function after we input something from the
keyboard.
For example:
Number only: <input name = "number" size = "8" maxlength = "8"
onkeyup = "numericOnly(this);"/>
RegExpObject.test(string): This method is used to see whether a
string matches a certain pattern.
For example:
<script type = "text/javascript">
var str = "Welcome to USA";
var patt1 = new RegExp("to");
var result = patt1.test(str);
document.write("Result: " + result);
</script>
You can run this demo to find the result yourself.
The result should be Result: true in the JavaScript alert box.
stringObject.replace(regexp,replacement): This method is used to
replace regexp with replacement string. regexp could also be a
substring using regular expression
For example:
<script type = "text/javascript">
var str = "Welcome to USA!"
document.write(str.replace(/USA/, "US"))
</script>
Regular Expressions: This is probably one of the most difficult
parts of the whole JavaScript knowledge. Regular expressions have
many simple expressions to implement a complex function. To have
good knowledge will help to make the development more efficient.
A regular expression consists of some metacharacters. Such a
normal letter includes alpha letters and numbers. Metacharacters
have special meaning, and some are explained below.
. (dot)
match any single character. e.g., b.t could match bat, bet, b t, but it
could not match the boat.
$
match line end. e.g., EUS$ could match "We are in EUS," but it
could not match "They are also EUScion."
\
This is the escape character in JavaScript. The character next to \
will be regarded as a normal character.
For example, \$ means dollar other than line end.
[]
This means any character in the [].
For example, b[ae]t could mean bat or bet, but not bot. – could mean
a range, e.g. [a-z] could mean alpha letter from a to z. And you could
use ^ here. e.g. [^168a-z] means any characters except 1, 6, 8 and
all small case alpha letters.
Some Useful Regulation Expressions:
E-mail format: \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

URL format: [a-zA-z]+://[^\s]*


Account name validation(begin with letter, length 5-16, number and
underline i.e.”_” allowed): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$
numbers(1-9)
^[1-9]\d*$
alpha letters(both uppercase and smallcase)
^[A-Za-z]+$
Demo that the Input Field Only Accept Alpha Letter in the Input
Field
<html>
<body>
<br>
Alpha Letters Only: <input name = "letter" size = "8" maxlength = "8"
onkeyup = "alphaOnly(this);"/>
<br>
<script language="JavaScript" type="text/javascript">
function alphaOnly(field) {
var validValue = /^[a-zA-Z]*$/;
if (!validValue.test(field.value)) {
field.value = field.value.replace(/[^a-zA-Z]/g,"");
}
return true;
}
</script>
</body>
</html>
Chapter 9: Coding Tips and Best Practices for
Asp.Net Web Application
This chapter provides coding tips and best practices to increase the
performance of an Asp.Net web application. C# and VB.net codes
are both complied into Microsoft intermediate language (MSIL),
which eliminates the difference in the performance of the application.
The choice of developing in C# or VB.net should not be based on
performance.
However, there are few do's and don'ts we can follow while coding
an Asp.Net web -application, to increase the performance
considerably.
StringBuilder Class over String
StringBuilder Class is preferred over String Class while working
with string manipulation operations. However, it's not always
recommended to do so. Sometimes usage of StringBuilder class
can undo the performance advantage it provides. StringBuilder
Class is recommended while performing insert/delete or formatting
of strings.
While performing string “replace” operations, String class is
preferred over StringBuilder. There is no significant advantage of
StringBuilder over String in Concatenate operations on a small
scale.
Therefore, as a thumb rule, we don’t want to use StringBuilder
when we don’t have very large strings and do not use a lot of string
operations (like append, remove, insert, delete). In this case, there
is no improvement in performance when MSIL is generated for the
same.
Since there is some overhead associated while StringBuilder
Object is created in memory, it’s advised to use StringBuilder only if
we are doing more than five-string manipulation operations.
Session State Usage
Turn off session state when not used
By default, the session state in asp.net is set to ON. Disable the
session state when not used. Session state value can be controlled
at the page level or application level.
We can use the EnableSessionState option in the @Page directive
to turn it turn off on a page as shown below.
<%@ Page EnableSessionState = "false" %>
To turn off session state at application level set the <sessionState>
mode value to off in web.config file.
Specify the session access level on the page
We can limit the session access permissions on a page based on
the usage by setting EnableSessionState to ReadOnly.
E.g., If we are just reading data from session objects on a page
and do not perform any write operations on it, we can set the
session state to read-only using
<%@ Page EnableSessionState = "ReadOnly" %>
Server-Side Vs. Client-Side Validation
Client-side validations are faster, but server-side validations are
reliable. Client-side validation provides instant feedback and saves
the CPU cycles, useful in low bandwidth scenarios. However, Java
scripts can be disabled rendering client-side validations obsolete.
Server-side validations are dependable. However, they use server
resources, and the latency and bandwidth usage from the return
trip slows down the site.
It’s generally recommended to use both types of validations. Apart
from ensuring integrity with the dual validation process, validations
on the client side provide instant feedback reducing the strain on
the server while uncaught validations on the client side are handled
at the server.
Page.IsValid and Validator Controls
It’s a good practice to check if the page is valid using Page.IsValid
when using validation controls, before going ahead with the
execution of the page. The validate method is automatically fired
when CausesValidation property is set to true. After the PageLoad
event is fired, the Validate method iterates through all the enabled
validation controls on the page, validating them.
Note: By default, all button controls have this property set to true.
HTML Footprint
Many of Asp.net controls are heavy in HTML. In the long run, it’s a
hindrance with respect to performance and scalability. Sometimes
we do not need the rich asp.net controls; we can use the HTML
tags with runat = “server” set.
E.g., Use literals instead of labels for a static display of text.
Literals generate far less HTML compared to labels.
E.g., Use repeater control over datalist/datagrid or dataview
controls. Though the other controls are easier to code when
compared to a repeater control, it is more efficient.
ViewState and ControlState
It’s a good practice to turn Off ViewState when form postback is not
used. By default page, ViewState is ON for all controls which slow
down the site. We can turn off the ViewState at the page level by
setting the attribute in @page directive, as shown below.
<% @Page EnableViewState = "false" %>
As a good practice, we can use ControlState instead of Viewstate.
Avoid Exceptions
Exception handling is very costly in terms of resource usage on the
server. Throwing and handling of unneeded exceptions are the
biggest resource hogs; cause the web/windows applications to
slow down.
Try to write code to avoid exceptions altogether. However, if
exceptions bound to occur, place the minimum possible code,
which might cause exception in the try block.
Always use the finally method to close connections to the
database, files, etc. Any input or output connections opened should
always be closed in “Finally” method, which is sure to execute
irrespective of an exception occurs or not.
Option Strict and Option Explicit
The explicit option ensures that all the variables are declared
before use. The strict option ensures that implicit data type
conversions happen only to widen conversions. It restricts when an
implicit data type conversion causes data loss.
Ex: Integer to Single, Long to Double
This is required when developing VB.NET applications, ensure that
both Explicit and Strict options are turned on in the visual studio.

1. On the Tools menu, choose Options .


2. Open the Projects and Solutions node.
3. Choose VB Defaults .
4. Modify the Option Strict setting.
Note: Setting Strict automatically enforces explicit.
Turn Tracing and Debugging Off
Tracing is a great tool while testing or for diagnosing the
application’s execution path and display diagnostic information at
runtime. Evidently, this is an overhead and causes the site to slow
down, hence ensure. Tracing is turned off in the production site,
where tracing is not required.
Debugging is a very handy tool while coding or issue isolation.
Sometimes, we forget to reset the debug flag in web.config, which
hinders the performance of the site.
Ex: enabling debugging doesn’t cache the scripts and images.
These are downloaded from the WebResources.axd handler every
time.
We can turn off tracing and debugging by editing web.config
<configuration>
<system.web>
<trace enabled = "false" pageOutput = "false" />
<compilation debug = "false" />
</system.web>
</configuration>
Deploy with Release Build
Make sure your production build is created by setting the
deployment type to Release mode in Visual studio. By default, it’s
in debug mode. Creating a build in debug mode overrides the
compilation setting web.config to true.
<compilation debug = "true" />
The code produced in release mode is more efficient and removes
the checks that are associated with the development phase of the
application. Leaving the debug mode ON actually changes how
and when the pages are compiled by the JIT, which hits the
performance by adding additional information for better interactive
debugging which is not required in production.
Debugging Tips for Dot Net Application
Most of the common runtime errors and exceptions encountered
while debugging a DotNet application can be avoided if proper
coding techniques followed.
Some of the common error encountered in the project, and its
resolutions are listed below:
Tip 1 : If you get any error while debugging, then check the
JavaScript path and the name of the JavaScript function called
through the HTML file.
Tip 2 : While adding a column with a blank header in the grid, add it
with multiple spaces as the header. Make sure that all such blank
columns have different headers.
dsDisc.Tables[0].Columns.Add(" ");
dsDisc.Tables[0].Columns.Add(" ");
Could not load type '<filenname>’
Tip: Include all the aspx files and related files in the project. This can
be done by right click on the file name listed in the solution explorer.
Tip 3 : Table (0) error
This error may occur if the wrong table name is passed to the stored
procedure through the data access layer. Just make sure that the
table name used exists in the database used for running the
application.
Tip 4 : ‘Input string not in correct format’ error
This error occurs while typecasting one data type to another.
For example: While casting a string with non-integer character to an
integer.
Tip 5 : ‘Column name not found’ error
The column-name specified in the Datagrid (formed through bound
columns) to display the data is not selected in the stored procedure
query.
For example: If no Request Date column is selected through a stored
procedure and the bound column in the Datagrid is:
<ASP:BOUNDCOLUMN datafield = "RequestDate" headertext =
"Request Date">
Tip 6 : Page is getting submitted even if the input values are invalid
This error occurs if Page. IsValid() is not checked in the code behind
file before any database operations. This function call checks the
isValid property of all the validations.
Page.Validate();
if(Page.IsValid == true)
{
// Code for database operation
}
Tip 7 : ‘Object Reference not found.’
This error occurs if any attribute or method of a null object is
accessed. Before referring to any attribute or method of an object,
make sure that the null condition is checked.
For example:
string strVar;
if ( strVar != null)
{
if(strVal.Equals(“”))
{
strVal = “value”;
}
}
Confirm that there is entries for Page_Load event handler in initialize
component method.
For example:
private void InitializeComponent()
{
this.Load += new
System.EventHandler(this.Page_Load);
}
This line is automatically generated when the code behind file is
coded for the first time.
Tip 8 : Always use the access specifier as protected or public for a
variable that has to be used in the HTML file.
Do not forget to import the namespace separately in the HTML file if
any class of that namespace is used there.
For example:
<%@ Import namespace = "AIRS.Common.Config" %>
if any of the class files present in Config namespace is used.
Tip 9 : ‘0 rows present in the dataset’ error
This error occurs if the dataset is not null, it has a table, but the table
does not have any row, and the user is referring to the 0th row in the
dataset.
A systematic procedure for debugging saves a considerable amount
of time while testing. Following are some of the steps to be followed:

1. To enable or disable the debugging, right-click on the


project name in the solution explorer. Then click on the
properties menu. In the window that appears, select
Configuration properties | debugging for various debugging
options.
2. Always set the mode in the toolbar combo-box as DEBUG(
not release) while using the debugger.
3. Always check for the correct file paths and database
names in the web.config file.
4. Don't forget to set the start page through the solution
explorer. This can be done on the right click of the file,
which has to be set as the first file of the application.
5. Put the breakpoints by pressing F9 or by using the left click
of the mouse at the desired statement.
6. The application can be started in debug mode by pressing
F5. Otherwise, use ctrl+f5 to start the application without
debugging.
7. Execution sequence for the user-controls and aspx files is

Code behind of aspx


Code behind of user-control
Html of user-control
Html of aspx
8. After starting the application in debug, mode following
options can be used -:

F5- to go to next breakpoint after executing the in-


between code
F11 - To go to the next statement
F10- to execute a function call without going inside the
function
During Debugging:

If you need to go to a certain logical point either forward or


backward, right-click on that particular line of code and
choose 'Set Next Statement,' or you can directly drag the
cursor to that point.
Instead of using breakpoint, 'Run To Cursor' can be used if
you don’t want the debugger to stop at a particular
statement every time.
For a scenario in which you have multiple files or a large
file, to locate the cursor, you can choose 'Show Next
Statement' options by right click on the code.
Watch For:

The value of a variable can be seen using a Quick watch


or Normal watch.
Both the watches can be added by using the Right Click
on the variable to be watched.
The Normal watch can also be added by selecting the
Debug | Windows | Watch from the main menu.
In quick watch at a time, only one variable can be seen,
and the user has to close the watch before going to the
next statement.
In normal watch, the user can add several variables and
see how their values get changed while the debugging
proceeds.
Remember not to add too many variables in the watch
window. It makes the debugging very slow.
Use a quick watch wherever possible.
Using immediate window option of debug windows, you
can directly assign values to simple variables
E.g., int, string, float, and test for further execution.
To see the variable definition or function implementation,
right-click and select the option for 'GO TO Definition.'
If there is any hidden control in your application. The
type of control can be made other than hidden to see the
value while debugging, or we can view the source code
through the browser.
Chapter 10: Advanced Strategies for Enhancing
ASP.NET Performance
This chapter is prepared for the benefits of developers using
ASP.NET 2.0 or above, to improve or enhance performance and
response time to end-users.
String Management
Use a StringBuilder class to perform two or more operations on the
string instead of the string object. The StringBuilder object is
preferable for concatenation operation if an arbitrary number of
strings are involved. Use the concatenation operator when
everything which needs to be concatenated is specified in one
statement.
What is the Exact Difference?
When manipulation is accomplished on a string object, the original
instance of the String object in memory will be wiped out, and a new
one will be placed which leads to memory de-allocation and
reallocation. The StringBuilder class resolves this difficulty by
preallocating an internal buffer to hold a string. The contents of this
string buffer are used directly.
Note: It's usually advisable to use a StringBuilder when performing
two or more string manipulations. (If it's only one change, copying
the value to and from StringBuilder will not result in better
performance.)
Turn Off Session State
Typically in a web application, there may be static as well as
dynamic pages. In the static pages, which do not require Session,
the Session State can be turned off. The pages which require
Session Data as ReadOnly, the SessionState can be made
ReadOnly.
To turn off Session State at the page level,
<%@ Page EnableSessionState = “False” %>
To make it Read-only at the page level,
<%@ Page EnableSessionState = “ReadOnly” %>
To implement session expiration for specific pages, add a <META>
tag to the HTML headers of the pages that require a valid session.
The session time-outs can be set in web.config to reflect on all the
pages of the application.
Set Session Expiration for specific pages,
<meta http-equiv = 'refresh' content = '60' />
Set Session time-out in Web config,
<system.web>
<sessionState timeout = "1" mode = "InProc" />
</system.web>
Using View State
View state allows the state to be persisted with the client, and it
requires no cookies or server memory to save this state. The View
State can be switched on and off at the Web Control level as well as
the Page-level.
Switch off View State for controls and pages that do not need it.
Use http://<host>/trace.axd to identify unneeded VIEWSTATE
It helps to retain the values among multiple requests on the same
page. The View State values are hashed, compressed, and encoded
to provide higher security than the hidden field. If larger values are
stored in the View State, it decreases the page loading and posting
performances. So it is preferable to store only lightweight data in the
view state.
Separation of Content and Logging
Separating the content and logs to different physical disks will
improve the performance due to the increased concurrency while
accessing content and writing the log data.
The location of the content and the IIS Logs should be a part of the
initial architecture design and be included in the build document
used to configure the application/server. As the load increases on
the server, it is advisable to move the IIS Logs away from the drive
where the content is located to gain better performance from the disk
subsystem.
IIS Log Optimization
The W3C Extended Log Format includes a lot of fields that can be
logged per request, and attention has to be given in selecting the
appropriate fields to optimize the writing performance to the disk.
Since fields like User-Agent, Referer can have variable-length
strings, unless the information provided by such fields is used for
analytic purposes, they can be ignored for really busy sites. IIS
Logging can also be disabled for static content like images to reduce
the writing overhead on the disk.
IIS Compression
IIS Compression can result in significant bandwidth savings. It
compress the static file types .htm, .html and .txt and also dynamic
file types .asp and .exe. After a few users have hit a site, we can
verify that compression is working by viewing the %WINDIR%\IIS
Temporary Compressed Files directory on a Web server. It should
contain multiple files, which indicates that static files have been
requested, and IIS has compressed a copy of them and stored them
on the local drive. When that file is requested again, whether it's the
same user or not, the compressed version of the file is served
directly from this folder. Dynamic files can be compressed as well,
but copies are not kept on the local Web server. It may be
advantageous to compress additional file types.
Connection Timeouts
Connection timeouts help reduce the number of memory resources
that are consumed by idle connections. When we enable connection
timeouts, IIS enforces the following types of connection timeouts at
the connection level:
A connection timeout, which triggers after the connection
between the client and the server has been idle for a while.
A request timeout, which prevents clients from issuing
unreasonably slow requests to the server (for example, 1
bit per second).
A response timeout, which can trigger due to the server not
being able to furnish the response in the time specified by
the timeout value.
The server usage needs to be reviewed, and user habits analyzed to
come up with an ideal value for the timeouts.
IIS Services
IIS is capable of hosting the following four services:

W3SVC: Web Service. Required for Hosting Web Sites.


FTPSVC: FTP Publishing Service. Required for hosting
FTP Sites.
SMTPSVC: Simple Mail Transfer Protocol Service.
Required for working with mail components on the web.
NNTPSVC: Network News Transfer Protocol Service.
Required for hosting news bulletins.
Enable only those services that are used to reduce the attack
surface and also to preserve the resources on the server. Please
review if FTPSVC and SMTP are required to be running.
Unnecessary Services
Windows servers, by default, have some services that are not
needed on a dedicated Web Server. Disabling the services that are
not needed releases the resources they consume and also reduce
the attack surface on the server. The security guide ( from
www.microsoft.com) is a good resource to follow when deciding what
services need to be enabled on the servers depending on the role
the server is destined for.
Constrain Unwanted Web Server Traffic
Limit the traffic in the Web Server to avoid unnecessary processing.
For example, block invalid requests at the firewall to limit the load on
the Web server. Also, do the following:

Map unsupported extensions to the 404.dll file in IIS.


Use the UrlScan filter to control the verbs and the URL
requests to allow.
Review your IIS logs. If the logs are full of traffic, then
investigate blocking that traffic at the firewall or filtering the
traffic by using a reverse proxy.
Disable Tracing and Debugging
In the production environment, to avoid the performance issues,
disable tracing and debugging configuration in the configuration file.
It can be disabled inside Machine.config file to affect all the
applications deployed in that server and also inside the Web.config
file in the particular application alone.
<Configuration>
<system.web>
<trace enabled = "false" pageOutput = "false" />
<compilation debug = "false" />
</system.web>
</configuration>
Make Sure Pages are Batch Compiled
The virtual address space will be split based on the number of
assemblies that are placed in the process. When the virtual address
space is fragmented, which leads to out-of-memory conditions.
ASP.NET compiles all pages that are placed in the same directory
into a single assembly for decreasing the number of assemblies
placed in the process. Below techniques helps to condense the
number of assemblies that are not batch compiled: Place multiple
languages in a separate directory. When placed in the same
directory, ASP.NET compiles a separate assembly for each language
in that directory.
Use of Server.Transfer and Response.Redirect
To navigate to the pages within the same application,
Server.Transfer is used. The Response.Redirect method should be
used when controls are transferred to pages in different applications,
and if authentication and authorization need to be ensured, then
Response.Redirect should be used for redirection.
Page Size Reduction
The frequently used static scripts on the web page can be referred
by including the <script> tag, which helps the client to cache these
scripts for consequent requests.
<script language = Javascript src = "datepicker.js">
To reduce the size of the web page, eliminate the characters such as
tabs and spaces before sending a response. These characters
create white spaces when it is included on the page. Refer to the
below samples to check the page size reduction. Create two
separate pages to copy the contents below and check page size.
// with white space
<table>
<tr>
<td>Good </td>
<td>Morning</td>
</tr>
</table>
// without white space
<table><tr><td>Good</td><td>Morning</td></tr></table>
Images
The size of the images placed in the web pages can be reduced to
trim down the page weight.
Create smaller versions of bloated icons.
Remove text from images where possible.
Reduce the whitespaces in webpages using a white-space reduction
tool that removes and compresses white spaces from HTML, CSS,
and Script files.
Explicitly Dispose or Close All the Resources
Even when an exception occurs, ensure that resources are disposed
of using try/finally block. Use finally clause to close the resources.
Create a connection when it is needed and end the connection once
the task is done. When different objects are used in the program,
make sure to call the Dispose or Close method of the object. When
the Dispose or Close method of the object is not invoked, it extends
the life of the object in memory. The shared resources such as
database connection and files should be closed explicitly.
Exception Management
To improve the performance and scalability of the application, handle
the exceptions effectively by identifying the causes of exceptions,
and writing the code to avoid exceptions. Consider the following
guiding principles to ensure optimum performance:

Implement a Global.aspx error handler.


Monitor application exceptions.
Use try/catch/finally on disposal resources.
Write code that avoids exceptions.
Caching
Caching technique aids in accumulating the data. The data, such as
page output or application data, will be stored in the client or the
server temporarily. The stored information will be recycled to meet
the consequent requests to avoid the difficulty in reconstructing the
similar data. The Cache uses the least recently used (LRU)
algorithm to remove the items automatically. The data stored in the
cache will be deleted or erased when the application restarts.
ASP.NET provides the following three caching techniques:

Cache API
Output caching
The partial page or fragment caching
Segregate Secure and Non-Secure Content
When a folder structure is planned for the website, under the virtual
root folder, create two separate subfolders to enclose public and
confidential files. The pages that hold sensitive information will be
stored under a confidential folder and secured using HTTPS instead
of enabling SSL for the complete website.
Only Use SSL for Required Pages
Identify the pages which enclose sensitive information and enable
SSL for those pages. The sensitive data, such as user login details,
passwords, and credit card numbers.
Ensure the below points are satisfied to enable SSL.

To encrypt the page data.


To guarantee that the server to which we send the data is
the server that we expect.
For pages which need SSL, follow these strategies:

Make the page size as small as possible.


Avoid using graphics that have large file sizes. Use
graphics that have smaller file sizes and resolution.
Data Binding
Use data binding effectively to keep away from performance
problems.
When Page.DataBind is called in a page, it recursively invokes this
page level DataBind for the controls on the page which supports this
functionality. So, instead of page-level databind, invoke the
DataBind for the controls which require databind.
The following line calls the page level DataBind.
DataBind();
The following line calls DataBind on the specific control.
ServerControl.DataBind();
Reduce Cookie Size
Cookies help to store user-specific information on the client-side. It is
a small file sent by the web server and stored on the client machine
by the web browser.

Reduce the size of the cookies.


Avoid sensitive data in Cookies. If needed, encrypt the
data and store it.
Use less number of cookies by eliminating unwanted
cookies.
When the application becomes ineffective, cookies should
expire immediately.
The performance tuning for ASP.net applications can be done by
using the strategies mentioned above.
Window Forms Optimization In .Net
This section contains C# coding tips to improve the loading time of a
window form at the designer level. There are requirements when we
want to optimize and speed up the loading time of the opening of a
window form. Speed improvement is noticeable when there are so
many controls on a single form, and even more when there are
controls like “Panel control,” which can have different controls in it.
The example below will help you in optimizing your code of designer.
Code Overview
The code is written in C# for windows application. In the project, it
was written with Dot Net compact framework 2.0 for pocket pc
application. There are two independent workarounds for optimizing
the controls load-time.
Part 1 - Creating the Controls in a Tree Manner (Top to the
down formation of controls)
Initializing the controls in a tree manner helps in improving the load
time by 40%. That means parent controls should be initialized first.
When we create the child node, parent ID should be specified
immediately after that.
Examples:

1. If there is a ‘Panel controls’ with many other child controls


on it, create a panel control first and specify the parent of
that control (usually the main form) and then add other
controls to the panel. Have a look at the following
example.

2. Also, use the .Parent property of the control instead of


adding the controls using ‘controls’ collection. This will
improve the performance for sure.
Code 1 - Default code:
private void InitializeComponent()
{
this.myPanel = new System.Windows.Forms.Panel();
this.txtName = new System.Windows.Forms.TextBox();
this.myPanel.SuspendLayout();
this.SuspendLayout();
// myPanel
this.myPanel.Controls.Add(this.txtName); // victim 1
this.myPanel.Location = new System.Drawing.Point(12,
26);
this.myPanel.Size = new System.Drawing.Size(173, 68);
this.myPanel.Name = "myPanel" ;
// txtName
this.txtName.Location = new System.Drawing.Point(50,
12);
this.txtName.Size = new System.Drawing.Size(100, 20);
this.txtName.Name = "txtName";
// Form1
this.Controls.Add(this.myPanel); // victim 2
this.myPanel.ResumeLayout(false);
this.myPanel.PerformLayout();
this.ResumeLayout(false);
}
Optimizing the above code using the top-down (tree) method will
result in the following code snippet.
Code 2 – Controls in tree manner, and using .Parent property:
private void InitializeComponent()
{
this.myPanel = new System.Windows.Forms.Panel();
this.txtName = new System.Windows.Forms.TextBox();
this.myPanel.SuspendLayout();
this.SuspendLayout();
// txtName // Moved up before panel
this.txtName.Location = new System.Drawing.Point(50, 12);
this.txtName.Size = new System.Drawing.Size(100, 20);
this.txtName.Name = "txtName";
// myPanel
this.myPanel.Location = new System.Drawing.Point(12, 26);
this.myPanel.Size = new System.Drawing.Size(173, 68);
this.myPanel.Name = "myPanel";
this.myPanel.Parent = this; // putting panel first and using
.Paren t
this.txtName.Parent = this.myPanel; // Using .Parent
// Form1
this.myPanel.ResumeLayout(false);
this.myPanel.PerformLayout();
this.ResumeLayout(false);
}
Part 2 – Minimize the Number of Method Calls
Another way to improve the loading time of a window form is by
minimizing the number of method calls, used by default mode in
form initialization.
Example: Code generated by the ‘form designer’ for setting the
‘location and size of control’ makes call to two methods Point() and
Size() for setting these properties, like below sample code:
Code snippet - 3:
// txtName
this.txtName.Location = new System.Drawing.Point(50, 12); //
Point()
this.txtName.Size = new System.Drawing.Size(100, 20); //
Size()
this.txtName.Name = "txtName";
// myPanel
this.myPanel.Location = new System.Drawing.Point(12, 26); //
Point()
this.myPanel.Size = new System.Drawing.Size(173, 68); //
Size()
this.myPanel.Name = "myPanel";
We can consolidate Point() and Size() methods into single
Rectangle() method and assign it to .Bounds property. So Code
Snippet 3 can be replaced by the code below.
Code snippet - 4: Using .Bounds and Rectangle()
// txtNam e
this.txtName.Bounds = new System.Drawing.Rectangle(50, 12,
100, 20);
this.txtName.Name = "txtName";
// myPanel
this.myPanel.Bounds = new System.Drawing.Rectangle(12,
26, 173, 68);
this.myPanel.Name = "myPanel";
These were very fruitful for the performance benchmarks, and even
improvement of half of a second was helpful. Using a combination of
both the tricks, we can get around 65% faster loading of forms.
Notes:

1. We need to modify the default code generated by visual


studio designer.
2. These changes should be done only on the final stage of
form designing. If someone makes any changes from the
GUI designer of form post these modifications, then all
will be rolled back to the default coding style.
3. It improves only from initialize time; the additional
components loading time will remain unchanged.
Chapter 11: Mobile App Development Using
Android Studio and Sencha
In recent times, most of the mobile technologies use Android OS.
Let us try to understand how Android Studio is different from
Eclipse and the uses of Android Studio for developing software
over Eclipse.
The aim is to provide basic information about the uses of Android
Studio over Eclipse IDE. We can have a basic understanding of the
IntelliJ IDEA IDE used in Android Studio. Also, we will get to know
the basic structure of IntelliJ IDEA.
Eclipse and Android Studio
Eclipse: Eclipse IDE (Integrated Development Environment) is a
platform that is used to develop/build the software and applications
using the components like jar files, libraries, plug-ins, etc. We can
use the Eclipse IDE to build the applications, mostly in Java.
Android Studio: Android Studio is an IDE used to create android
applications. It has the IntelliJ IDEA, which is just another IDE as
Eclipse that contains most of the features associated with it. Some of
the features are listed below:

The Gradle based build system is used to build, test, run, and
package the project without being an overhead.
Build variants consist of two factors. Debug and Release.
Build types define the process of how the module is built. And
build flavor defines the resources of the module that is going
to build (resources may be the Source code, for example).
Code templates are provided by Android SDK, which
provides the templates used to create and run the application
instantly. It helps the developer to proceed with the
development in the right direction.
Android Studio helps the developer to create an application
by the feature of drag and drop of the theme, wherein the
theme would be added in the application in no time.
Lint tool is provided by Android Studio to check any
performance/ structural/unused codes from the module,
which adversely affect the application by unnecessary
compilation and processing of the code which is not required.
We can correct the errors projected by the Lint tool so that
the performance can also be maximized.
IntelliJ IDEA
IntelliJ IDEA is an IDE that stands for Intelli gent J ava IDEA, which
is used in Android Studio for developing the application software
mostly for mobiles and tablets.
It supports languages like Java, XML, HTML, XHTML, JavaScript,
SQL, and so on.
The technologies and frameworks supported by IntelliJ IDEA are
AJAX, EJB, Hibernate/JPA, JSF, JSP, Spring, Struts2, Struts, Web
Services, WebSphere, Glassfish, etc.
Structure of IntelliJ IDEA
Project and its Components :
The project is known as Modules in Android Studio. It consists of
components like Modules, Facets, different types of libraries, SDK,
and so on. Each component is described below.
Project: Projects consist of the source codes, libraries, and build
files consolidated in it. It can have collections consisting of modules
and libraries. Depending on the complexity of the project, there can
be a single-module project or multi-module project.
Module: Module is an individually separate functionality that consists
of the source codes, build files, web.xml, unit tests, etc. We can
perform many actions on it, such as run, test, debug. A module can
depend on other modules in a multi-module project. Modules can
have a common SDK or it can also be defined for each module
independently.
Facets: A facet represents a specific configuration for a particular
framework/technology associated with the module. For Ex: Java-
related projects in Eclipse will have Project Facets in the Properties -
> Project Facets for a particular project. Each module can have
multiple Facets associated with it.
Library: Library is an archive of compiled code that the module
depends on (Ex: JAR Files). There are three types of libraries
supported by IntelliJ IDEA. They are as follows:

1. Module Library: Module libraries are the java class files


that are accessible within the module. The details of
these libraries will be stored in module*.iml files in the
workspace.
2. Project Library: Project libraries are the java class files
that are accessible to the modules within the project as a
project contains one or more modules within it. The
details of these libraries will be stored in module*.jpr files
or in .idea/library file.
3. Global library: Global libraries are the java class files
that are accessible to the different projects that contain
modules in it. The details of these libraries will be stored
in applicationLibraries.xml or the .config directory.
SDK: Every project uses the Software Development Kit (SDK). For
Java projects, SDK is referred to as JDK (Java Development Kit). It
determines the API libraries to be used to build the project. If the
project is a multi-module project, then the project SDK, by default,
will be common for all the modules. Also, there is an option to
configure individual SDK for each of the modules.
Structure of IntelliJ IDEA: The IntelliJ IDEA project consists of
many modules. Each module will have the Source Code, Unit Tests.
It also contains the Order entities like SDK and Libraries along with
it. It might also have one or more Project Facets, which helps in
configuring the IntelliJ IDEA. In the example shown above is
assumed to have two modules.
Basic Understanding of Android Studio over
Eclipse IDE
This section explains the basic comparison between Angular Studio
and Eclipse IDE.
In Eclipse IDE, we have the concepts called Projects and libraries. In
Android Studio, we have replaced the Projects with “Modules” and
“Libraries.” The definitions of the two have given above.
Each module has its own Gradle Build File (It means that the build
file is generated automatically for the new module / we can create
the build files manually if we are importing the existing Eclipse
Projects). The Gradle build files consist of important information such
as the supported android versions, dependencies, and other meta-
data related to the project.
Android Studio has advanced features when compared to Eclipse
IDE.
Some of them are as follows:
i) Code Editing: Android Studio provides the code editing
feature which can be used while creating an application.
Some of the features are as follows:
(a) Alt+Enter key is used to fix any errors present in the
project, either it will completely fix the error or suggest
you with the possible solutions.
(b) Ctrl+D key is used to duplicate the code. We can
select the line that has to be duplicated and click on the
Ctrl+D key so that it can duplicate the entire code for
us.
ii) Sample Importing and templates: Android Studio has a new
user interface that contains dialog boxes that enable the
user to create a new application with the project templates
and code samples provided by Google.
iii) Internationalization string editing: An android developer can
grasp the features such as code completion, refactoring, and
code analysis through Android studio.
iv) User interface design: The developer can use this feature to
edit and preview the layouts with multiple screen sizes,
languages, and other criteria.
Including the Jar dependencies: Just like in Eclipse IDE, we need to
add the JAR files to the modules in Android Studio. There will be a
lib directory where we can place all the jars.
The exception from Eclipse is that, in Android Studio, all we need to
do is just right click .jars in the lib directory and click on “Add to
Libraries.” This will automatically add all the jars as Gradle
dependencies in the Gradle build file of the particular module. This is
hassle-free which saves the effort of adding the jars manually.
Always click on “Sync Gradle” to make sure that the module has
been notified with all the dependencies present in the build file.
Sencha Cordova App - Tips and Tricks
Environment Set Up Guide
If the project targets Android, iOS alone, then one machine – MAC
OS alone - is enough; if the project targets for windows as well,
then a windows machine is a must. Targeting mostly the windows
platform since it is the platform that causes many issues.
For the Windows Phone environment:

1. A windows 8 desktop/laptop is required.


2. For windows setup, please follow the below steps:

1. Install “Microsoft Visual Studio Professional 2012.


2. Download windows phone SDK from the official
website and run it.

3. Have windows account created- HDFC parent account or


normal account. To create a normal account please below
the steps:

Steps to create a Microsoft:

Hit https://signup.live.com on your browser. (You can


also google as “create a Microsoft account”)
You will be directed to a page where you will be
prompted to enter some personal details like name,
date of birth, and a username and password.
After entering all these, click on Create Account.

Your account is created.

4. Once the SDK is installed, go to window start and type


“Windows Phone Developer Registration” and click on that
5. Connect the device and register the device – you should
get some message like this “Your phone is unlocked for
development,” and the button will be turned now to
unregister.
Build Process
When a sencha project folder is created, that project has to be
initiated for Cordova to use the Cordova plus points.
Command to generate a new app in cmd.exe inside the folder
where you want to create the project.
Sencha generate app <appname> <path of the project>
When the project needs to use Cordova, we have to initialize it, use
the below command for the same after navigating to your project
folder.
Sencha cordova init “package name.”
Usually, the package name is the bundle identifier in iOS.
When you want to add plugins which we need to use in the app,
download the plugins, and keep in a folder. Then navigate to
Project->Cordova folder ->Plugins and then type the below
command:
Cordova plugin add <path where the plugin is there in the
system>
To check all the list of plugins added to the device:
Cordova plugin list
To build a specified platform, please follow the steps below.
Change the platform to be the desired platform in
app.json – ios, android, wp8
Any config.xml changes required like adding icons can
be done
Then run the command: Sencha app build
native>log.txt
Once the build is succeeded, get into the path project->cordova-
>platforms->respective platform folder-> and check for the apk,
.xcodeproject or .xap file.
Android: The .apk will be in Android->build->outputs->.apk. Install
the apk file and check-in device directly.
iOS: .xcode project will be created. Double click on the project, it
will open in Xcode.
In general, settings, check for bundle identifier, a device targeted
for this app, and in build settings, set the code signing identities
and provisioning profile and run the app in the device.
Windows:

1. .xap is placed inside the Bin folder. Connect the device to


the desktop/laptop
2. Go to windows start and type “Application Deployment.”
3. The tool will be open, select the option to be device and
browse to the location of the .xap file and click deploy
4. Once the deploy is mentioned as complete in tool. You can
use the application.
Sencha Issues in Windows Build, and it’s Solution

1. Sencha Message Box goes beyond the device width and


doesn’t wrap.

Sencha Message Box doesn’t take the parent width and height,
so max-width and min-width property should be set in the
message box element. See the example below.
createNewMessageBox: function(){
var newMsgBox = new Ext.MessageBox();

newMsgBox.defaultAllowedConfig.showAnimation = false;
newMsgBox.defaultAllowedConfig.hideAnimation
= false;
newMsgBox.setHeight('auto');
newMsgBox.setWidth('80%');
newMsgBox.setMaxWidth('300');
newMsgBox.setPadding('5%');
return newMsgBox;
},
messageText = '<div style = "white-space:normal
!important; word-break:break-word !important; min-width:320px;
max-width:320px>'+”Sample message text”+'</div>';
var showVCAlertMsg =
this.createNewMessageBox();
showVCAlertMsg.show({
itemId:'showVCAlertId',
message: messageText,
scope:this,
buttons: [
{
itemId: 'okVC',
text: 'OK',
ui:'plain',
width:'200px',
height:'40px',
margin:'2% 0 4% 2%',
style:'background-image: none; background-color
: #0067ac; color:#ffffff; border-radius: 0;font-size:18px;'
}
],
fn: function(response) {
}
});
},
2. Title bar goes up and never comes down when the input
field is focus.

In all places where the title bar is gone up, either in a blur of that
input field or hide event of mask element, put window.scrollTo(0,
0)
For mask element:
component..on(hide, function() {
window.scrollTo(0, 0)
},component);
In Controller for input element:
blur:’resetTitleBar’
resetTitleBar: function(){
window.scrollTo(0, 0);
}
3. Sencha select field is not clickable on the right portion of the
field.

The select field component is having some constrained width, so


use the css for the select field to have the min-width:320px;
max-width:320px;
4. Sencha select field pops up the keypad and dismisses
before displaying the picker field.

Customize the select field, and in the initialize method, detect


the touch start event and call the picker and blur the dom input.
On the usual masktap, do not call the picker.
component.element.on('touchstart', function() {
me.showCalendar();
component.input.dom.blur();
}, component);
5. Sencha select field icon not appearing.

For windows alone in media queries, assign a background


image, position, and no-repeat for this select field with
respective icons.
6. Date formatting not working in windows and hangs the
application

Check the format used for date formatting, only / is compatible


with windows, manually format date easily.
7. Page going beyond the device width and height with
scrolling enabled.

Set the page panel css min-width and Max-width to the desired
pixels.
Push Notification Environment Pre-requisites in all Platforms
Cordova plugin for push notification can be used in sencha.
iOS:

For IOS, we will be using the APNS library.


We need .p12 and .cer file and the password which was
used while exporting the file.
We need Device token which unique to a mobile number
from mobile
Procedure to get these details:
In the app, when we register, we will get a device token, which
needs to be sent to the server, which sends the payload to the
APNS server, which in turn sends the push notification to the
device.
In the member center, for the app, we can enable push notification
and create the certificate signing request from keychain access
from MAC and upload the same in the SSL certificate creation
section for Push and get the .cer files for the sandbox and
production environment.
Windows:

For Windows Phone, we will be using WNS service.


We need Channel URI which is unique to each mobile
device from the mobile app
We need Package SID and Client secret
Procedure to get these details:
From plugin, you will get channel URI from the app.
In your app record in your windows DEV center, the App identity
section gives you all the details below.
Package/Identity/Name XXXXX
Package/Identity/Publisher CN = YYYYYY
Package/Properties/PublisherDisplayName HDFC Standard Life
Insurance Company Limited
Package Family Name (PFN) aaa.bbbbbbbbbb
Package SID cccccccccccccccccccc
You can share this link to help customers find your app in the Store.
And in the App settings section under push notification, you will get
the secret key.
Package SID:
ms-app://dsaddsf-sfsdfdsf-dsgfdsfdfgdg-dgdfhggfhfhgfh-fjhgjhgjgjhgj-
gfjkjhjkhjkgjk-gjgkhjkkh-kgkjhjkljl.nm-vh-fhjgjhgjgj
Application identity:
<Identity Name="HDFCLife.HDFCGeoFencingApp"
Publisher="CN=sadsfsfsfdsfdgffdgf-dgfdgfhgf-dgdgfhgfg-fdfgffhf" />
Client ID:
000adsfdgryr6577687654658769709870
Client secret:
Ohhgjgjgjghjghjgjgjgj/sffdgfgfhfhghjvjgjg
Android:

For Android, we will be using the GCM service.


We need sender Id, which is Project number and App ID
which API Key from developer’s login.
We need a device ID, which is a Registration Id that is
unique to each mobile from the mobile App.
Backbase Mobile SDK
It describes typical mobile application development using Backbase
Mobile SDK and issues faced during development.
Overview of Backbase CXP Mobile SDK
CXP Mobile is a mobile application development platform (MADP)
which is designed to help customers to produce and maintain their
mobile applications. The CXP Mobile SDK is the term given to the
product and components which are shipped together to form CXP
Mobile.
The main CXP Mobile SDK features include:

The ability to help customers develop entirely new mobile


applications from scratch.
The ability to enrich previously existing mobile applications.
Support for both iOS (7.x and higher) and Android (4.x and
higher).
Support for rendering (Launchpad-based) widgets in a
native container with the ability to navigate between
widgets using native transitions.
Extending widgets with native capability using out-of-the-
box and custom-built widget features.
App management, including Navigation, Page, Widget, and
Content Management.
A dedicated backend (MBaaS) with JWT authentication
support and additional mobile-specific services.
Development tools to develop and test widgets in a mobile
environment more easily.
Implementing the Backbase CXP Mobile SDK solution produces a
mobile application that uses a combination of native components
and web items (such as widgets and containers). This increases
the ability to reuse content and functionality across platforms. As
Backbase CXP Mobile is built on top of the existing operating
systems, mobile applications are using native user interface (UI)
components to build navigation structures and transitions between
functionality. As a result of this, the mobile application is responsive
and aligns with the user interface guidelines for the used platform.
The CXP Mobile SDK is split into three parts. These are:

MBaaS — the backend mechanism is serving


mobile optimized and mobile-specific data services.

Library — an iOS and Android-compatible


framework that can be embedded in new and already existing
mobile applications and offers developers a set of functions
to, amongst other things, render widgets.

Templates — native mobile application


projects that can be compiled into real mobile applications. It
links the widgets, library, and native components together.
Solving Problems with App Development
1. The mobile app isn’t able to hit server using HTTPS for
communication (SSL Pinning)
Backbase SDK Version: 1.2.0
Issue: The mobile application wasn’t able to hit the backend
server, which was using the https protocol for communication.
Status Code 404 was received as a response from the server
while trying to use its services.
The server was using a self-signed certificate, which was added to
the mobile application under the ‘assets/backbase’ path.
Resolution Action : Backbase SDK 1.2.0 doesn’t support SSL
Pinning using Self-Signed Certificates. Higher SDK versions
(>1.2) support SSL Pinning now.

2. Device Login Issue

Backbase SDK Version: 1.3.2 +


Issue: The mobile application wasn’t able to log in while running
the application on an Android or an iOS device. The login
functionality was, however, working fine on emulators.
All the necessary service calls were returning success status code
(200) as responses from the server for both device and emulator.
The one difference between the device and the emulator was the
network connectivity. The Android devices were using WiFi for
connectivity, but the emulators were using the system LAN
internet for the same.
Flow of the requests on LAN and WiFi were:
Emulator: Mobile App -> via LAN Internet -> Application Server
Device: Mobile App -> via WiFi -> via Proxy Server -> Application
Server
Model.json is retrieved from the application server for the first time
when the app launches. This file provides page information for the
pre-login widgets. Once the user logs in, model.json is fetched
from the server for a second time, which contains the page
information for the post-login widgets and replaces the first file.
The proxy server in the WiFi route was caching the first
model.json that we retrieve from the application server. Due to
this, when the second request for model.json was sent from our
application, the proxy server provided the cached file instead of
letting the request go to the application server.
Resolution Action: The proxy server was removed from the WiFi
route by removing the application server URL from the firewall of
the WiFi. Due to this, our application was able to communicate
directly with the app server without any caching happening in
between.
3. Backbase supports versions of iOS and Android

Backbase SDK Version: 1.3.2 +


Issue: There are a few OS versions for Android and iOS for which
Backbase doesn’t provide support yet or has withdrawn their
support. Below is the list of those versions:

iOS - 7 (Support from Backbase will be withdrawn


January’16 onwards)
iOS - 8
iOS - 9
Android 4.X
Android 5.X
Android 6.X (Backbase found some problems with SSL
pinning in Android 6.0 with trusted certificates and thus
are not providing any support for the same. Fixes and
support will probably start from February’16 onwards)

Due to certain APIs not supported by Backbase Mobile SDK,


issues are prone to come if we are building our mobile app for the
unsupported versions. For example, at present, as no support is
available for Android 6.0(Marshmallow), the mobile app being
developed for the same API using Backbase Mobile SDK won’t
execute.
Resolution Action: Backbase SDK 1.2.0 doesn’t support SSL
Pinning using Self-Signed Certificates. Higher SDK versions
(>1.2) support SSL Pinning now.
4. Single Page and Multi-Page Architecture for Portals
URL: N/A
Backbase SDK Version: 1.3.2 +
Issue: Backbase CXP provides several containers which assist a
developer in creating web portals. These containers allow
developers to position the widgets as per their choice. For
example, the Launcher Deck container follows a Panel-Widget
format due to which Panels are created on the left-hand side, and
their respective widgets are opened on the right-hand side. Please
find below the screenshot explaining the same.
Such containers are, however, not supported by Backbase Mobile
SDK at present. Due to this, the entire widget information that we
require to create the mobile app is not present in the model.json
file. Containers specific for mobile are still being
envisaged/developed by Backbase.
Due to this, a Single-Page Architecture, where all widgets reside
in a single page, inside a single container, differentiated only by
permissions is not achievable with Backbase Mobile SDK.
Resolution Action: A Multi-Page architecture, having one page
per widget, is achievable with Mobile SDK. We get all the widget
information in our model.json file correctly. The individual pages
appear in the Hamburger Menu (for Android) or the native iOS
menu as individual components. Upon clicking one page, the
respective widget would open up on the mobile screen.
5. App crash on Android platform

Issue: The Mobile application was crashing on various Android


devices.
It was then established then in Android webview 48 and above,
the application was crashing.
Resolution Action: In backbase SDK, there is a method that is
used to subscribe to events in PubSubs. The method is called in
the javascript realm every time a call is made to method
gadget.pubsub.subscribe and it was triggering a memory issue in
Webview version 48 and above.
This method was like this:
@org.xwalk.core.JavascriptInterface
@android.webkit.JavascriptInterface
public Map<String, PubSub> subscribe(String eventName) {
The method was returning a Map of the subscribed events. This
map was not used in javascript at all.
Conclusion
So this was all about the advanced methods and strategies you can
use to learn the best coding practices for various programming
languages such as Java, ASP.NET, JavaScript, Swing, HTML, and
Mobile App Development. By learning these methods and strategies,
you will become a master of advanced coding, and your code will
have the best performance in terms of speed, reliability, portability,
and reusability.
We covered all the major aspects like best design practices, best
coding practices, performance tuning of your code, Android studio
app development, and Sencha Cordova App. I hope you liked the
book and best of luck on your clean coding adventures.

You might also like