Wednesday 4 January 2017

Java Coding Standards

Java Coding Standards

1.     Introduction


The intent of this document is to create a guide for software source code quality based on Java Standard. The guidelines appearing herein apply to anyone who creates, modifies or read software source code for Java.
This document is not a description of a complete software process. A particular group will need to develop their own methodologies and procedures for the specification, design, implementation, testing and deployment of their software systems. This document is simply a set of rules to follow during the implantation phase that will help produce a high quality result.

2.     What this process will achieve


You can hope to achieve three goals by requiring a consistent source code style.

  • ·        Improving the productivity of existing programmers.
  • ·        Allow new programmers to become comfortable with existing source code in less time than would otherwise be necessary.
  • ·        Allow existing programmers to move around to different projects easily without having to adjust to the programming style in use by other groups.
Standardizing the "look and feel" of the source code will reduce the time to market, it will reduce the time spent correcting problems in the product line, and it will give engineers the flexibility to jump on and off projects without a large learning curve. This means that you will be able to spend less time on legacy products and jump into the more interesting task of designing and implementing future products.

3.     Java


This Document delves into some fundamental java programming techniques and provides a rich collection of coding practices to be followed by JAVA/J2EE based application development teams for Java.
This document is written for Java software developers to help them:

  • ·        Write java code that is easy to maintain and enhance
  • ·        Increase their productivity

3.1.  Standards for Classes, Interfaces, Packages, and Compilation Units

3.1.1.  Standards for Packages

3.1.1.1.      Naming packages

The rules associated with the naming of packages as follows:
Unless required otherwise, a package name should include the organization’s domain name, with the top level domain type in lower case ASCII letters i.e. com.<Name of company> followed by project name and sub project name as specified in ISO Standard 3166, 1981.
Eg:- com.<companyname>.<modulename>.<other>
Subsequent components of the package name vary according to requirements.
Package names should preferably be singular.

                 3.1.1.2.      Documenting a Package

There should be one or more external documents in html format with the package name that describe the purpose of the packages documenting the rationale for the package, the list of classes and interfaces in the package with a brief description of each so that other developers know what the package contains.

3.1.2.  Standards for Classes

Naming Classes:
Class names should be simple full English descriptor nouns, in mixed case starting with the first letter capitalized and the first letter of each internal word also capitalized. Whole words should be used instead of acronyms and abbreviations unless the abbreviation is more widely used than the long form, such as URL or HTML.

Class Visibility:
Package or default visibility may be used for classes internal to a component while public visibility may be used for other components. However, for a good design, the rule is to be as restrictive as possible when setting the visibility. The reason why the class is public should be documented. Each class should have an appropriate constructor.


Documenting a Class:
The documentation comments for a class start with the header for class with filename, version, copyright and related information. The documentation comments should precede the definition of a class and should contain necessary information about the purpose of the class, details of any known bugs, examples etc. as illustrated in. The development/maintenance history of the class should be entered as comments in the configuration management tool at the time of baselining the source code and in the file header as well.

3.1.3.  Standards for interfaces

The Java convention is to name interfaces using mixed case with the first letter of each word capitalized like classes. The preferred convention for the name of an interface is to use a descriptive adjective, such as Runnable or Clone able. Interfaces should be documented specifying the purpose of the interface and how it should and shouldn’t be used. Method declarations in interfaces should explicitly declare the methods as public for clarity.

3.1.4.  Standards for Methods

Naming Methods:
Methods should be named using a full English description, using mixed case with the first letter of any non-initial word capitalized. It is also common practice for the first word of a method name to be a strong, active verb. e.g. getValue(), printData(), save() ,delete(). This convention results in methods whose purpose can often be determined just by looking at its name. It is recommended that accessor methods be used to improve the maintainability of classes.

Getters:
Getters are methods that return the value of a field. The word ‘get’ should be prefixed to the name of the field, unless it is a boolean field where ‘is’ should be prefixed to the name of the field.  e.g. getTotalSales(), isPersistent(). Alternately the prefix ‘has’ or ‘can’ instead of ‘is’ for boolean getters may be used. For example, getter names such as hasDependents() and canPrint() can be created. Getters should always be made protected, so that only subclasses can access the fields except when an ‘outside class’ needs to access the field when the getter method may be made public and the setter protected.


Setters:
Setters, also known as mutators, are methods that modify the values of a field. The word ‘set’ should be prefixed to the name of the field for such methods type. Example: setTotalSales(), setPersistent(boolean isPersistent)

Getters for constants:
Constant values may need to be changed over a period of time. Therefore constants should be implemented as getter methods. By using accessors for constants there is only one source to retrieve the value. This increases the maintainability of system.

Accessors for collections:
The main purpose of accessors is to encapsulate the access to fields. Collections, such as arrays and vectors need to have getter and setter method and as it is possible to add and remove to and from collections, accessor methods need to be included to do so. The advantage of this approach is that the collection is fully encapsulated, allowing changes later like replacing it with another structure, like a linked list.
Examples: getOrderItems(), setOrderItems(), insertOrderItem(), deleteOrderItem(), newOrderItem()

Method Visibility:
For a good design, the rule is to be as restrictive as possible when setting the visibility of a method. If a method doesn’t have to be private then it should have default access modifier, if it doesn’t have to be default then it should be made protected and if it doesn’t have to protect only then it should be made public. Wherever a method is made more visible it should be documented why.
Access modifier for methods should be explicitly mentioned in cases like interfaces where the default permissible access modifier is public.

Standards for Parameters (Arguments) to Methods :
Parameters should be named following the same conventions as for local variables. Parameters to a method are documented in the header documentation for the method using the javadoc@param tag.
However:
  • ·        Cascading method calls like method1().method2() should be avoided.
  • ·        Overloading methods on argument type should be avoided.
  • ·        It should be declared when a class or method is thread-safe.
  • ·        Synchronized methods should be preferred over synchronized blocks.
  • ·        The fact that a method invokes wait should always be documented.
  • ·        Abstract methods should be preferred in base classes over those with default implementations.
  • ·        All possible overflow or underflow conditions should be checked for a computation.

There should be no space between a method/constructor name and the parenthesis but there should be a blank space after commas in argument lists.

3.1.5.  Naming Convention Standards

Naming Variables:
Use a full English descriptor for variable names to make it obvious what the field represents. Fields, that are collections, such as arrays or vectors, should be given names that are plural to indicate that they represent multiple values. Variable names should not start with an underscore _ or dollar sign $ characters and should be short and meaningful. The choice of a variable name should be mnemonic i.e., designed to indicate to the casual observer the intent of its use. Single character variable names should be avoided except for temporary “throwaway” variables.

Naming Components:
For names of components, full English descriptor should be used, post fixed by the Component type. This makes it easy to identify the purpose of the component as well as its type, making it easier to find each component in a list. Therefore names like NewHelpMenuItem, CloseButton should be preferred over Button1, Button2, etc.

Naming Constants:
Constants, whose values that do not change, are typically implemented as static final fields of classes. They should be represented with full English words, all in uppercase, with underscores between the words like FINAL_VALUE.

Naming Collections:
A collection, such as an array or a vector, should be given a pluralized name representing the types of objects stored by the array. The name should be a full English descriptor with the first letter of all non-initial words capitalized like customers, orderItems, aliases.

Naming Local Variables:
In general, local variables are named following the same conventions as used for fields, in other words use of full English descriptors with the first letter of any non-initial word in uppercase. For the sake of convenience, however, this naming convention is relaxed for several specific types of local variable like Streams, Loop counters, Exceptions. Name hiding or data hiding refers to the practice of naming a local variable, argument, or methods the same or similar as that of another one of greater scope in same or super class. This may lead to confusion and should be avoided.

Naming Streams:
When there is a single input and/or output stream being opened, used, and then closed within a method the common convention is to use ‘in’ and ‘out’ for the names of these streams, respectively.

Naming Loop Counters:
Loop counters are a very common use for local variables therefore the use of i, j, or k, is acceptable for loop counters where they are obvious. However, if these names are used for loop counters, they should be used consistently. For complex nested loops the counters should be given full meaningful English descriptors.

3.1.6.  Comments on class methods

Each method should declare the javadoc tags exactly in the sequence as given below. Each line item begins with an asterisk. All subsequent lines in multiline component are to be indented so that they line up vertically with the previous line. For reference, the javadoc tags are explained in detail in Annexure.
Example:
/**
* Description:
* @param <Mandatory Tag> for description of each parameter
* @return <Mandatory Tag> except for constructor and void>
* @exception <Optional Tag>
* @see <Optional Tag>
* @since <Optional Tag>
* @deprecated <Optional Tag>
*/

3.1.7.  Best Practices:

Efficient String Concatenations
For making a long string by adding different small strings always use append method of java.lang.StringBuffer and never use ordinary ‘+’ operator for adding up strings.

Optimal use of Garbage collection
For easing out the work of java Garbage Collector always set all referenced variables used to ‘null’ explicitly thus de-referencing the object which is no more required by the application and allowing Garbage Collector to swap away that variable thus realizing memory.

Use variables in any code optimally
Try to make minimum number of variables in JSP/Java class and try to use already made variables in different algorithms shared in same JSP/Java class by setting already populated variable to ‘null’ and then again populating that variable with new value and then reusing them.

Try to reduce the number of hits to database
Number of hits to the database should be reduced to minimum by getting data in a well arranged pattern in minimum number of hits by making the best use of joins in the database query itself rather than getting dispersed data in more number of hits.

Heavy Object should not be stored in sessions
Storing heavy objects in the Session can lead to slowing of the running of the JSP page so such case should be avoided.

Always use database connection pooling
Always use javax.sql.DataSource which is obtained through a JNDI naming lookup. Avoid the overhead of acquiring a javax.sql.DataSource for each SQL access. This is an expensive operation that will severely impact the performance and scalability of the application.

Release database resources when done
Failing to close and release JDBC connections can cause other users to experience long waits for connections. Although a JDBC connection that is left unclosed will be reaped and returned by Application Server after a timeout period, others may have to wait for this to occur. Close JDBC statements when you are through with them. JDBC ResultSets can be explicitly closed as well. If not explicitly closed, ResultsSets are released when their associated statements are closed. Ensure that your code is structured to close and release JDBC resources in all cases, even in exception and error conditions.

Minimum use of System.out.println
Because it seems harmless, this commonly used application development legacy is overlooked for the performance problem it really is. Because System.out.println statements and similar constructs synchronize processing for the duration of disk I/O,they can significantly slow throughput.

Synchronization has a cost

  • ·        Putting synchronized all over the place does not ensure thread safety.
  • ·        Putting synchronized all over the place is likely to deadlock.
  • ·        Putting synchronized all over will slow your code and prevent it from running when it should. This accounts for memory leaks.

3.1.8.  Technical points

Apart from the standards mentioned already following should be considered while writing java

  • ·        Instance /class variables should not be made public as far as possible.
  • ·        A constructor or method must explicitly declare all unchecked (i.e. runtime) exceptions it expects to throw. The caller can use this documentation to provide the proper arguments.
  • ·        Unchecked exceptions should not be used instead of code that checks for an exceptional condition. e.g. Comparing an index with the length of an array is faster to execute and better documented than catching arrayOutOfBoundsException.
  • ·        If Object.equals is overridden, also override Object.hashCode, and vice-versa.
  • ·        Override readObject and writeObject if a Serializable class relies on any state that could differ across processes,including,in particular,hashCodes and transient fields.
  • ·        If clone() may be called in a class, then it should be explicitly defined, and declare the class as implements Cloneable.
  • ·        Always use method equals instead of operator == when comparing objects. In particular, do not use == to compare Strings unless comparing memory locations.
  • ·        Always embed wait statements in while loops that re-wait if the condition being waited for does not hold.
  • ·        Use notifyAll instead of notify or resume when you do not know exactly the number of threads which are waiting for something
  • ·        When throwing an exception, do not refer to the name of the method which has thrown it but specify instead some explanatory text.
  • ·        Document fragile constructions that have been used solely for the sake of optimization.
  • ·        Document cases where the return value of a called method is ignored.
  • ·        Minimize * forms of import Be precise about what you are importing.
  • ·        Prefer declaring arrays as Type[] arrayName rather than Type arrayName[].
  • ·        StringBuffer should be preferred for cases involving String concatenations. Wherever required String objects should be preferably created with a new and not with the help of assignment, unless intentionally as they remain in the String pool even after reference is nullified.
  • ·        All class variables must be initialized with null at the point of declaration.
  • ·        All references to objects should be explicitly assigned ‘null’ when no more in use to make the objects available for garbage collection.
  • ·        As far as possible static or class fields should be explicitly instantiated by use of static initializers because instances of a class may sometimes not be created before a static field is accessed.
  • ·        Minimize statics (except for static final constants).
  • ·        Minimize direct internal access to instance variables inside methods.
  • ·        Declare all public methods as synchronized.
  • ·        Always document the fact that a method invokes wait.
  • ·        Classes designed should be easily extensible. This will be very important in the event that the currently designed project needs to be enhanced at a later stage.
  • ·        It is very important to have the finally clause (whenever required) because its absence can cause memory leakage and open connections in a software.


 Thanks



25 comments:

  1. Yay, this is the post I've asked for! To be frank, I'm identify myself as a pure newbie in the backend and Java is the very first coding language I'm learning) I don't have any practices yet, but my book-learning knowledge is pretty extensive now :D So I know what is string pool in java https://explainjava.com/java-string-pool/ at least. And the courses I'm reading now are providing such comprehensive info, but I'm looking for other sources in order to compare them, so this one of yours is the one I need!

    ReplyDelete
  2. These standards are very popular but I would like to pay your attention to the special coding structure being applied here.

    ReplyDelete
  3. The job of a coder first and foremost is to tell an accurate and complete story of the patient's encounter based on (and only based on) the documentation.best office chair for lower back pain

    ReplyDelete
  4. Without a full understanding of what you need to be able to do and how to encode, you will not be able to get any benefit from these programs, so you should study this issue of the basics.

    ReplyDelete
  5. I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. creare sito ecommerce

    ReplyDelete
  6. Web hosting is actually a much simple concept than most people make it out to be. Also, there are numerous web hosting plans on the market today - how do you know which one is for you? Here's a brief look at web hosting, what it means, and which plan you should pick. https://onohosting.com/

    ReplyDelete
  7. coding school online for kids I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.

    ReplyDelete
  8. Here are a few rules for right coding of skin sores:
    https://hostinglelo.in/

    ReplyDelete
  9. circumstance is most appropriate to an expert code advisor who comprehends the varieties in codes from one area to another. https://onohosting.com/

    ReplyDelete
  10. I'm a learner charge counselor working in a little duty consultancy close to London. Having shown up in London from Germany 8 years prior for a hole year experience, I was unable to have envisioned that one day I would wind up turning into a UK charge counsel. These days, I can't envision a superior occupation for myself. https://sites.google.com/view/seoservicesindelhiindia

    ReplyDelete
  11. So who tests merchant items (Common Off The Shelf) for web application security issues before they are moved into creation conditions? https://twitchviral.com/

    ReplyDelete
  12. Hey There. I found your blog using Google. This is a very well written article. I’ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I’ll definitely return.Regularly scheduled programming

    ReplyDelete