Java Coding Standards and Best Programming Practices

  1. Naming Conventions and Standards

    Note:

    The terms Pascal Casing and Camel Casing are used throughout this document.

    Pascal Casing – First character of all words are Upper Case and other characters are lower case. Example: BackColor

    Camel Casing – First character of all words, except the first word are Upper Case and other characters are lower case.
    Example: backColor

    1. Class Names – Use Pascal casing for Class names. Class names should be nouns and preferably whole words. Use of abbreviations should be discouraged unless the abbreviations are more commonly used than their full forms (like HTML, PDF etc).

    public class HelloWorld

    {

    ...
    }

    2. Method Names – Use Camel casing for Method names. Methods should be verbs and describe what the method achieves in business logic.

    public void sayHello(String userName)

    {

    ...
    }

    3. Variables – Use Camel casing for variables.

    int totalCount = 0;

    void sayHello(String userName)
    {
    String fullMessage = "Hello " + userName;

    ...

    }

    4. Interfaces – Use Pascal casing for Interfaces (e.g: interface InterestCalculator;)

    5. Constants – The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores. E.g: int MIN_WIDTH = 1;

    6. Do not use Hungarian notation to name variables. In earlier days most of the programmers liked it – having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

    string m_sName;
    int nAge;

    However, in java coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

    7. Variable names should be short yet meaningful. The usage of one letter variables must be avoided except for throwaway variables (e.g: inside a loop or counter).
    Good:

    String addressLine1;
    int baseSalary;

    for(int i = 0; i < count; i++ )

    {
    ...

    }

    If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

    Not Good:

    int sal;
    String clr;

    8. Do not use underscores (_) for local variable names.

    9. Do not use variable names that resemble keywords.

    10. Prefix boolean variables, properties and methods with “is” or similar prefixes. Ex: private boolean isFinished; private boolean hasPrevInterest;

    11. Package names should follow the standard pattern

    com….
    Eg: com.coolcodings.search.funkytown.reporting;

    12. File name should match with class name with the same case (Pascal casing). For example, for the class HelloWorld, the file name should be HelloWorld.java.

DukeJuggle

      1. Indentation and Spacing

        1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.

        2. Curly braces ( {} ) should start in the same line and end in the same indentation level as the conditional clause.

        3. Use one blank line to separate logical groups of code.

        Good:
        String SayHello ( String userName) {
        StringBuilder fullMessage = new StringBuilder();
        fullMessage.append(“Hello “);

        If (username != null) {
        fullMessage .append(username);
        } else {
        // Append generic user label
        fullMessage.append(“Generic User”);
        }

        // return full message
        return fullMessage;

        }

        4. There should be one and only one single blank line between each method inside the class.

        5. Use a single space before and after each operator and brackets.

        Good:
        if ( isShowResult)
        {

        for ( int i = 0; i < 10; i++ )
        {

        //
        }

        }
        Not Good:
        if(showResult==true)

        {
        for(int i = 0;i<10;i++)

        {
        //

        }
        }

        6. Keep private member variables, properties and methods in the top of the file and public members in the bottom.

Duke_Int_Float_Char

  1. Good Programming practices

    1. Avoid passing data between screens using “Get” parameter. Use POST method wherever possible.

    2. Avoid writing very long methods. A method should typically have 1~40 lines of code. If a method has more than 40 lines of code, you must consider re factoring into separate methods.

    3. Method name should tell what it does. Do not use misleading names. If the method name is obvious, there is no need of documentation explaining what the method does.

    Good:
    void savePhoneNumber ( String phoneNumber )
    {

    // Check for valid phone number format, then save phone number.
    }

    Not Good:

    // This method will save the phone number.
    void saveNumber ( string aNumber )
    {

    // Save the phone number.
    }

    4. A method should do only ‘one job’. Do not combine more than one job in a single method, even if those jobs are very small.

    Good:

    // Save the address.
    // saveEmailAddress ( emailAddress);

    // Send an email to the supervisor to inform that the address is updated.
    // sendEmail ( emailAddress );

    Not Good:

    // Save address and send an email to the supervisor to inform that
    // the address is updated.

    // updateEmailAndNotify( address, email );

    void updateEmailAndNotify ( String address, String email )
    {
    // Job 1.

    // Save the address.
    // ...

    // Job 2.

    // Send an email to inform the supervisor that the address is changed.

    // ...

    }

    5. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value.

    Good:

    If ( memberType == eMemberTypes.Registered )

    {
    // Registered user… do something…

    }
    else if ( memberType == eMemberTypes.Guest )

    {
    // Guest user... do something…
    }
    else
    {

    // Un expected user type. Throw an exception

    throw new Exception (“Unexpected value “ + memberType.toString());
    // If we introduce a new user type in future, we can easily find
    // the problem here.
    }

    Not Good:

    If ( memberType == eMemberTypes.Registered )

    {
    // Registered user… do something…

    }
    else

    {
    // Guest user... do something…

    // If we introduce another user type in future, this code will

    // fail and will not be noticed.
    }

    6. Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it in your code.

    However, using constants are also not recommended. You should use the constants in a config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed.

    7. Do not hardcode strings. Use resource files.

    if(string.Compare(name,“john”,false) == 0)
    {

    //… name equals to john
    }

    10. Use String.isEmpty() instead of “” whenever possible.

    11. Avoid using member variables. Declare local variables wherever necessary and pass it to other methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.

    12. Use enum wherever required. Explicitly assign values starting with None = 0 .

    Good:
    enum MailType {

    None=0,
    Html = 1,

    PlainText =2,
    Attachment =3

    }

    void SendMail (String message, MailType mailType) {

    switch ( mailType ) {

    case MailType.Html: // Do something break;

    case MailType.PlainText: // Do something break;

    case MailType.Attachment: // Do something break;

    default:

    // Do something break;
    }
    }

    Not Good:

    void sendMail (String message, String mailType)
    {

    switch ( mailType )
    {

    case "Html":

    // Do something break;
    case "PlainText":

    // Do something break;
    case "Attachment":

    // Do something break;
    default:

    // Do something break;
    }
    }

    12. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.

    13. The event handler should not contain the code to perform the required action. Rather call another method from the event handler.

    14. Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.

    15. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.

    16. Never assume that your code will run from drive “C:”. You may never know, some users may run it from network or from a “Z:”.

    17. If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.

    18. Error messages should help the user to solve the problem if it is of an expected origin. Never give error messages like “Error in Application”, “There is an error” etc. Instead give specific messages like “Failed to update database. Please make sure the login id and password are correct.”

    19. When displaying error messages, in addition to telling what is wrong, the message should also tell what the user should do to solve the problem. Instead of message like “Failed to update database.”, suggest what should the user do: “Failed to update database. Please make sure the login id and password are correct.”

    20. Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.

    21. Whenever possible, do not have more than one class in a single file.

    22. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.

    23. Avoid public methods and properties, unless they really need to be accessed from outside the class.

    24. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure.

    25. If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”.

    26. Logically organize all your files within appropriate folders. Use 2 level folder hierarchies. You can have up to 10 folders in the root folder and each folder can have up to 5 sub folders. If you have too many folders than cannot be accommodated with the above mentioned 2 level hierarchy, you may need re factoring into multiple packagesd.

    27. A good logging class needs to be create, which can be configured to log errors, warning or traces. If you configure to log errors, it should only log errors. But if you configure to log traces, it should record all (errors, warnings and trace). The log class should be written such a way that in future you can change it easily to log to Windows Event Log, SQL Server, or Email to administrator or to a File etc without any change in any other part of the application. Use the log class extensively throughout the code to record errors, warning and even trace messages that can help you trouble shoot a problem.

    28. Declare variables as close as possible to where it is first used. Use one variable declaration per line. Do not declare all variables at the top of the function.

    29. Use StringBuilder class instead of String when you have to manipulate string objects in a loop.

    Consider the following example:

    public String composeMessage (String[] lines)

    {
    String message = “”;

    for (int i = 0; i < lines.Length; i++)

    {
    message += lines [i];

    }

    return message;
    }

    In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it.

    If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object.

    See the example where the String object is replaced with StringBuilder.

    public String composeMessage (String[] lines)

    {
    StringBuilder message = new StringBuilder();

    for (int i = 0; i < lines.Length; i++)

    {
    message.append( lines[i] );

    }

    return message.toString();
    }

    30. Use Conditional operator (?:) instead of if else condition for assigning a value based on a given criteria where applicable
    Eg: allNumberTabs = fragments.Contains('A') ? "1" : "0";

    31. Whenever possible, use non synchronized data structures instead of their synchronized alternatives. E.g : Use StringBuilder instead of StringBuffer if there is no need for synchronization.

    32. Do not comment out code as the code is being refactored. Rather, delete the code to reduce confusion for later maintenance. The old code can always be retrieved from Source Control.

  1. Architecture

    1. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.

    2. Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.
    3. Always use caution when using database resources and pools. Make sure the connections are released and assigned to null after proper code execution.
    4. When architecting systems, make sure that there are no single point of failures for the sake of scaling applications.
    5. Whenever possible, include code reviews and usage of profiling tools in the project lifecycle so that quality is assured and there is less time spent in fixing the issues after the code is shipped.

  1. Comments

    Good and meaningful comments make code more maintainable.

    1. Summary information needs to be added after a method is defined (hitting /* on top of the method will automatically generate most part of it).

    2. Comments should be in the same level as the code (use the same level of indentation).
    3. Use // or /** for comments. Rather than using comments on every line, try to summarize what you are doing in a block so it is easier for maintenance.

    4. If you have to use some complex or weird logic for any reason, document it very well with sufficient comments.

    5. If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.

    TODO Statements

    Utilize TODO statements in your JAVA code whenever you create code that is temporary (e.g. placeholders for unavailable features) or requires some attention at a future date. TODO statements show up in the most s IDEs and alerts other developers visiting the code that something requires TLC. Not doing so greatly increases the odds of missing things and creating bugs.

Duke-Throw-shirt-268x300

  1. Exception Handling

    1. Never do a catch exception and do nothing’. If the exception is hidden, one will never know if the exception happened or not. Do not use this as a handy method to ignore non-significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

    2. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

    3. Always catch only the specific exception, not generic exception.

    Good:

    void SeadFromFile (string fileName)
    {

    try
    {

    //read from file.
    }

    catch (FileIOException ex)
    {

    // log error.

    // re-throw exception depending on your case. throw;
    }

    }

    Not Good:
    void ReadFromFile ( string fileName )

    try
    {

    // read from file.
    }

    catch (Exception ex)
    {

    // Catching general exception is bad... we will never know whether

    // it was a file error or some other error.
    // Here you are hiding an exception.

    // In this case no one will ever know that an exception happened.

    system.out.println(“An exception Occurred!”);
    }

    }

    4. There is no need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an ‘unexpected general error’, this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to ‘ignore and proceed’.

    5. When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.

    Good:

    catch

    {
    // do whatever you want to handle the exception

    throw;
    }

    Not Good:

    catch (Exception ex)

    {
    // do whatever you want to handle the exception

    throw ex;

    }

    6. Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

    7. Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

    8. Write your own custom exception classes if required in your application. Avoid defining generic exception from Exception class and use more appropriate inbuilt exception classes (if not custom), where ever possible like ArgumentException for invalid parameters etc.

Advertisements

About javaclaus

Java Programmer, Code master, mountain biker, snowboarder, etc.
This entry was posted in Best Practices, Java, Software Programming and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s