Public:Coding conventions

From YaddaWiki

Jump to: navigation, search

Contents

Coding Conventions

All ICM development must stick to the following rules about code formatting, conventions etc.

Please, adjust your IDE to match the code formatting patterns described below.

Java coding conventions

We follow the Java code conventions and JSP code conventions with some customization and specific rules which are described below.

Class code sections

To improve the readability of classes we have decided to divide their code into logical sections:

  • CONSTRUCTORS - class constructors
  • GETTERS - Java Beans getters
  • TESTS - test methods in test classes
  • LOGIC - public methods of a class that implement its intended functionalities, e.g. Parser.parse(String) or Math.divide(), Court.addDivision(Division).
  • PRIVATE - class and package private methods
  • SETTERS - Java Beans setters
  • HashCode & Equals - hashCode and equals methods
  • toString - toString method
  • INNER CLASSES - inner classes


The order of the sections in a class should be the same as on the list above.


The exception to this rule are methods providing data for parametrized test methods. They can be placed directly above the test methods that use the provided data.

One class per file

Write only one class per java file. You are allowed to create multiple inner classes when it is reasonable. However, you are not allowed to have more than one highest level class in a java file.

Spacing/indentation

  1. never use tabs to indent, use 4 spaces instead of one tab
  2. if possible break lines longer than 120 chars, try not to excees 160 chars.
  3. use 80 chars for javadocs

One line if-s

Excerpt from code conventions:
Braces are used around all statements, even singletons, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

Access modifiers

Do not use "public" and "abstract" modifiers for interface methods. They are superfluous.

Naming things

Naming parts of code properly is one of the most important things to guarante the code to be readable and clear. The name should clearly indicate what a given part of the code is or does.

Module naming conventions

The name of the module should clearly express the functionality the given module provides, and should be preceded by the name of the application. Let's say the name of the app is football and the module we want to write will be responsible for the persistence layer access(saving, reading, repositories). In such a case the name of the module could be football-persistence.

Package name conventions

We divide the applications by functionalities they provide, not the types of services they are. It doesn't matter if you create a module, a package, a class or a method, the most important thing is that the name should correspond to the functionality the given fragment of the code provides (at least it's first part, e.g. JournalSearchController). It means that instead of package structure like this:

- controller
- service
- dto
...

We would have, for example:

- journal
  - details
  - search
- article
  - details
  - search
- search-common
- security

It's worth noting that it very often doesn't make sense to create a package unless there are at least a few classes (let's say 3-6) that could make up its content. For example, if we had a journal package and only three classes in it, let's say JournalDetailsController, JournalEditController<code> and <code>JournalEditService we probably wouldn't divide the package into journal.details and journal.edit packages. </code>

Interface and implementation naming

Avoid using IName for the interface name. An interface should be named without leading I.

Good:

SomeService

Bad:

ISomeService

The following rules apply to implementation naming:

  • use a reasonable prefix to explain the specifics of the implementation, eg.:
JdbcCatalog
CachedCatalog
  • if there is a really, really only one reasonable implementation of the interface (and you do not expect to ever have another one) you may also use: <Interface name> + Impl, eg.:
SomeServiceImpl

Loggers and logging

SLF4j is since now official logging tool (classes shall use slf4j logging classes and never use other loggers). Details: logging in Yaddda

Avoid commiting files with warnings

You should not commit files that have warnings shown by Eclipse or any editor you use.

In eclipse, to avoid warnings informing about unused imports you can use a feature called "Automated formatting and import clean up". This will allow eclipse to organize imports and to format the code before saving each java file.

To enable it, you have to select Window->Preferences item from the main menu. Then select Java->Editor->Save Actions option.

Expected settings are:

  • enable "Perform the selected actions on save"
  • enable "Organize imports"
  • you can also enable "Format source code" but only "Format edited lines", to avoid unnecessary noise in repo commits.

Coding guidelines

Exception handling

It is forbidden to catch an exception silently

Every exception must be handled properly (shown to a user, logged etc.). Never, ever do anything like this:

    try {
       ...
    }
    catch(Exception e) {}

Exceptions and threads

Be aware that exceptions raised in manually created threads are silently skipped. Check against any exceptions in the thread code:

 MyThread extends Thread {
     public void run() {
         try {
            //thread execution code
         } catch (Exception e) {
            //exception handling code
         }
     }
 }
 

And whenever starting specific thread it is preferable to use Future, DeskLightTask (in DL) or other class that does proper exception handling.

Iteration

Instead of this:

Iterator<Foo> it = foos.iterator();
while (it.hasNext()) {
    bar(it.next());
}

use this:

for (Foo foo : foos) {
    bar(foo);
}

Comments

Comments are usually helpful for other developers who need to read and maintain the existing code. Please, keep in mind, that a comment should be clear, concise and only written if really needed because we prefer to write readable code rather than extensive comments.

Format

We write comments in HTML5 format as described in the general javadoc rules

General rules

We write all comments in English. You are advised to use spellchecker feature of IDE to maintain reasonable standards.

We write comments for every interface and its methods. As a rule we also write comments for each public class and method. However, if a sensible comment for a class or method is not possible and the comment would only repeat the information contained in the class/method name then one can omit writing it as long as it is accepted by their Code Review peer.

Example of comments that are redundant and not really necessary:

/**
* Converter that translates a journal data transfer object into a view object.
*/
 @Service
 public class JournalDTOToVOConverter {
   /**
    * Converts the given journal data transfer object into a view object.
    *
    * @param journalDTO journal to convert, required not null
    * @return view object for the user interface layer
    */
   public JournalVO convert(JournalDTO journalDTO) {

Preamble

[suspended, TBD]

Each file must have preamble with:

  • copyright note (ICM, Warsaw University)
  • license note (Usually apache 2.0)

Class comments

Comment on a class should explain:

  • what the class is
  • what it is for
  • who the authors are (note: if you do some extensive work on a class, put yourself on the author list together with the previous ones).

Interface comments

It is obligatory to write extensive javadoc for every interface, no exceptions. This includes:

  • interface itself javadoc (what it is, what functionality represents etc.)
  • full javadoc for every method

Remember that comments describe the contract of an interface, both for users and those who will implement it. If it is clear then less problems will occur at the integration time.

Method comments

Comment on a public method should describe its usage, functionality, exceptions, params and return value. The comment should also explain the expected behaviour in border cases (what will happen if passed Collection is null? NullPointerException, or will it be treated as empty list?)

Field/ accessor method comments

If get/set methods are present for a field, the `get` method is preferred to add javadoc. Idem per idem is not acceptable (i.e. 'setCatalog: this sets the catalog property).

Personal tools