Coding for Beginners, 2020
Coding for Beginners, 2020
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();
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 ");
}
}
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.
String.equalsIgnoreCase() method:
Example:
package com.rule;
class Specify_StringBuffer_capacity_violation1
{
private StringBuffer sb = new StringBuffer(); //
VIOLATION
class Specify_StringBuffer_capacity_correction1
{
private final int SIZE = 10;
private StringBuffer sb = new StringBuffer(SIZE); //
CORRECTION
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.
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)
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;
}
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;
....
}
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
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:
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>
element = document.FormName.elements;
for(i = 0; len = element.length; i < len; i++)
{
document.write("The field name is: " + element[i].name");
}
</script>
alert (finalCount);
Before using the script, get the three arrays used in the script.
Arrays used in the JavaScript:
// 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+)*
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.
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:
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.
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: