Vous êtes sur la page 1sur 22

Best Coding Practices

File Organization

 Java source are named as *. java while the compiled Java byte code is named as *.class file. Each Java
source file contains a single public class or interface. Each class must be placed in a separate file. This also
applies to non public classes too.

 If a file consists of sections, they should be separated by blank lines and an optional comment, identifying
each section. Files longer than 2000 lines should be avoided.

 Java classes should be packaged in a new java package for each self contained project or group of related
functionality.

 Preferably there should be an html document file in each directory briefly outlining the purpose and structure
of the package.

 Java Source files should have the following ordering: Package and Import statements, beginning comments,
Class and Interface Declarations.
2
File Organization

 There should not be any duplicate import statement. There should not be any hard coded values in code.

 Hard coding of messages makes it hard to internationalize a program.

 Hard coding paths make it hard to adapt to another location.

 Application file structure can be categorized as below.


– Module structure
– Package structure
– Class structure

3
Coding comments

 Add the following to the beginning of all of your source files:

/************************************************
*
* Author Assignment Class Approved by Modified Date
<Your name> <Assignment name> <CSI class name> <Managers name> <date of modification/creation>
<Your name> <Assignment name> <CSI class name> <Managers name> <date of modification/creation>
*
*
************************************************/

 Add JavaDoc to all of your code, including classes, methods, etc. Before submission make sure that you can
run the JavaDoc export without any errors or warnings.

4
Coding comments

 Use @ to define values like @author, @param, etc.

/**
* Adds two ints (a+b) and returns the result
*
* @param a first integer to add
* @param b second integer to add
*
* @returns the sum of a+b
* @throws OverflowException
* if a+b exceeds the value representable by int
*/

5
CR coding comments

 When working on CR’s for specific clients, add comments above the lines of logic being written

/************************************************
*
* Author CR No. Class Approved by Modified Date
<Your name> <CR No.> <CSI class name> <Managers name> <date of modification/creation>
<Your name> <CR No.> <CSI class name> <Managers name> <date of modification/creation>
*
*
************************************************/
 When the line of CR logic has been completed, add end comments
/* End of <CR No.>*/

6
Coding comments

 Do not add extraneous information to method JavaDoc like method name.

 Individually and meaningfully comment member variables and class constants.

 Obvious/obfuscated comments are useless. Do not use them.

 Properly (but reasonably) comment your code. A developer should be able to get a general idea of what’s
going on by just reading comments (and no code).

 Check your comments for spelling and grammatical errors.

7
Indentation

 Spaces should be used as the unit of indentation. The indentation pattern should be consistently followed
throughout.

 Left and Right braces


– The starting brace should be at the end of the conditional and the ending brace must be on a separate
line and aligned with the conditional. It is strongly recommended that all conditional constructs define a
block of code for single lines of code.

 Wrapping Lines
– Lines longer than 80 characters should be avoided. When an expression will not fit on a single line, it
should be broken according to these general principles:

 Break after a comma.


 Break after an operator.
8
Indentation

 Prefer higher level breaks to lower level breaks. (in other words avoid breaking nested expressions).

 Align the new line with the beginning of the expression at the same level on the previous line.

 If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 4
spaces instead.

Example:
count = number.calculate(bytes, offset, length,
value, 0, estimatedCount);
long value = ((totalValue < plannedValue ) ?
totalValue : plannedValue );

 White Space and Blank lines improve readability by setting of sections of code that are logically related.
9
Indentation

 Two blank lines should be used in the following circumstances:


– Between sections of a source file
– Between class and interface definitions

 One blank line should always be used in the following circumstances


– Between methods.
– Between the local variables in a method and its first statement.
– Before a block or single line comment.
– Between logical sections inside a method to improve readability.
– Before and after comments.

10
Naming conversions

 Avoid Pointless Names and Give Meaningful Names.

 Prefer shorter name over longer one, if it reveal intent clearly.

 Use Consistent Naming, Avoid Synonyms and Avoid Similar Names.

 Prefer descriptive name over short form.

 Java Coding Convention.

 Avoid using non ASCII characters and words from local language.

 A class name should be noun (Employee,) and method names should start with verb (get, set,).

11
Naming conversions

 There are following points should be follow by each developers.


– class name->should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread
etc.
– interface name->should start with uppercase letter and be an adjective
• e.g. Runnable, Remote, ActionListener etc.
– method name->should start with lowercase letter and be a verb
• e.g. actionPerformed(), main(), print(), println() etc.
– variable name->should start with lowercase letter
• e.g. firstName, orderNumber etc.
– package name->should be in lowercase letter
• e.g. java, lang, sql, util etc.
– constants name->should be in uppercase letter.
• e.g. RED, YELLOW, MAX_PRIORITY etc.

12
Declarations

 Avoid creating unnecessary objects and always prefer to do Lazy Initialization.

 Never make an instance fields of class public.

 Always try to minimize Mutability of a class.

 Try to prefer Interfaces instead of Abstract classes

 Always try to limit the scope of Local variable

 Try to use standard library instead of writing your own from scratch.

 Wherever possible try to use Primitive types instead of Wrapper classes.

13
 Use Strings with utmost care.

 Always return empty Collections and Arrays instead of null

 use Defensive copies mechanism

 Rule of 30
– Methods should not have more than an average of 30 code lines (not counting line spaces and
comments).
– A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.
– A package shouldn’t contain more than 30 classes, thus comprising up to 27,000 code lines.
– Application with more than 30 packages should be avoided. Such a subsystem would count up to 900
classes with up to 810,000 lines of code.

 Our goal is to keep our overall system small while we are also keeping our functions and classes small.
Remember however that this rule is the lowest priority of the four rules of Simple Design. So, although it’s
important to keep class and function count low, it’s more important to have tests, eliminate duplication, and
express yourself. 14
SQL Usage

• Database Connection Pooling

• Hikari CP
HikariDataSource dataSource = new HikariDataSource(config);
Connection conn = dataSource.getConnection();

• Close all resources in finally block


finally{
try{ statement.close; resultSet.close(); con.close(); }catch(Exception e){ … }
}

15
SQL Usage

• Hard Parse Vs Soft Parse

• Use Bind variables for soft parsing

//Wrong Usage
for(int id=1; id<100; id++)
stmt.executeQuery(“SELECT * FROM CUSTOMER WHERE CUST_ID=” + id);

//Correct Usage
stmt = conn.prepareStatement(“SELECT * FROM CUSTOMER WHERE CUST_ID=?”);
for(int id=1; id<100; id++) {
stmt.setInt(1, id); stmt.executeQuery();
}

16
SQL Usage

• SQL Injection

• Use Bind variables to avoid SQL injection

//Wrong Usage
SELECT * FROM CUSTOMER WHERE CUST_ID=” + id); //Hard Parsing
SELECT * FROM CUSTOMER WHERE CUST_ID=” + (1234 + “ OR 1=1) // SQL Injection

//Correct Usage
stmt = conn.prepareStatement(“SELECT * FROM CUSTOMER WHERE CUST_ID=?”);
id=1234 + “ OR 1=1”
stmt.setInt(1, id); stmt.executeQuery();

17
Memory Handling

• Use primitive types.


Use int instead of Integer, long instead of Long.

• Nullifying the reference object

String data = readFromFile(“1_gb_file”);


//Do some computations on data
data = null;

• Static data (fields and members) are loaded into memory on class loading and remain until the
class is unloaded from memory (typically on JVM termination).

18
Memory Handling

• JVM memory parameters


Use -Xmx to specify the maximum heap size
Use -Xms to specify the initial Java heap size
Use -Xss to set the Java thread stack size

• Use memory profiling tools


VisualVM (https://visualvm.github.io/index.html)
Your Kit (https://www.yourkit.com/)
Jprofiler

19
Library Usage

• Selecting library
Use only active libraries
Check for library updates
Do Regression testing

• Using library
Don’t prefer download jar method
Use build tools like Maven(https://maven.apache.org/), Graddle (https://gradle.org/)

20
Tools

• Check Style (http://checkstyle.sourceforge.net/)


Checkstyle is a development tool to help programmers write Java code that adheres
to a coding standard. Checkstyle is a static code analysis tool used in software development
for checking if Java source code complies with coding rules.

• Find Bugs (http://findbugs.sourceforge.net/)


FindBugs is an open source static code analyser which detects possible bugs in Java
programs.

21
DIGITAL BUSINESS
DEMANDS NEW
ARCHITECTURE

MAKE
Corporate Headquarters
THE
LEAP!
Intense Technologies Limited
A1, Vikrampuri
Secunderabad – 5000 09. Telangana, INDIA
Tel: +91-40-44558585 / 27849019 / 27844551
Fax: +91-40-27819040
e-mail: internationalsales@in10stech.com

Branches
UK | USA | SINGAPORE | UAE
22

Vous aimerez peut-être aussi