Skip to content

Project Code Convention

Lucas Brilhante edited this page May 16, 2016 · 10 revisions

Table of Contents

  1. Naming Files
  2. Classes
  3. Methods
  4. Attributes/Variables
  5. Line Length
  6. Comments
  7. Keys & Indent
  8. Test
  9. Exceptions
  10. Asserts
  11. A Very Brief Example

1. Naming Files

All the project file's content must be named in English. The name of the files in Java must have the same name of the Class. Java establishes an order that must be used in the file:

Example:

/************************
 * Class name: Course (.java)
 *
 * Purpose: Class that modeling and control course's atributtes.       
 ************************/

package models;

import android.database.SQLException;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;

public class Course extends Bean implements Parcelable {
	
    private int id = 0;
    private String name = "";

    public Course() {
		this.id = 0;
		this.identifier = "course";
		this.relationship = "courses_institutions";
	}

...

}

2. Classes

The name of the classes must begin with capital letter in the singular, and must not be abbreviated. The following rules must be followed:

  • Names made by multiple letters must follow the standard UpperCamelCase, where each word will begin with a capital letter.
  • The name must not have any characters other than the letter of the alphabet.

The functional order of the components of the class are:

  • Constants
  • Attributes of the class
  • Attributes of the instance
  • Constructors
  • Main methods
  • Helper methods

Example:

public class Book extends Bean {
    private int id;
    private int integralText;
    private int chapters;
    private int collections;
    private int entries;

    public Book() {
        this.id = 0;
        this.identifier = "books";
        this.relationship = "";
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

3. Methods

All methods will have their initial & final parameters without a space between the opening and closing of their parenthesis. Each aditional parameter will have a comma at the end of the following and a ' '(space) for the beginning of the new parameter.

  • Methods must be named in lowerCammelCase.
  • Methods needs a verb to describe the action he execute.

Example:

public boolean insertBean(Bean bean) throws SQLException {
    ...
}

4. Attributes/Variables

The attributes must follow this formatting standard:

  • Only one declaration in each line.
  • The names must follow the standard lowerCamelCase.
  • They can't be abbreviated.
  • They can't have special characters.
  • For constant names with two names, they need to be separated with the underscore and be written all with capital letters.
  • Global variables should not be used, but if it must then it shall follow the java pattern: NAME_NAME

Example of variables:

public class Article extends Bean {
    ...	
    // Correct way.
    private int publishedJournals = 0;
    
    // Wrong Way
    private int publishedjournals = 0;

    // Wrong Way
    private int PublishedJournals = 0;

    // Wrong Way
    private int PUBLISHEDJournals = 0;
    ...
}

Global variables examples:

public class CourseListFragment extends ListFragment {
    ...	
    // Correct way.
    private static final String ID_INSTITUTION = "idInstitution";
    
    // Wrong way
    private static final String ID_institution = "idInstitution";
    
    // Wrong way
    private static final String Id_Institutions = "idInstitution";
    ...
}

5. Line length

Avoid lines longer than 80 characters. When a statement won't fill in a single line, it may be necessary to break it.

6. Comments

Comments should be used only when talking about context. The code should be self explanatory. Except in the beginning of classes and public methods, in which must be used java doc docummentation comments.

The comments must be initialized first with capital letter. At their end, it must be add a '.' (dot) to indicate it's end.

6.1 Method Comments

To document a public method, you must use the type '/** & */, and to start typing there must be a space. The comments also should include the tags @param for the parameters, @returns for the return value and @throws to explain the exception that the method throws. The comment after the tag should be under the tab and have four tabs.

Example of Method comment:

    /**
      * Adds the data from an institution objects into the SQL database.
      *
      * @param institution
      *           Institution object which contains the data to be added to the database.
      * @return
      *           Boolean ( 0, 1) that represents the response from the database.
      * 1 (true) means sucess, 0 (false) means failure.
      * @throws SQLException
      *           Means that there were a problem inserting the data into the database.
      */
      public boolean addInstitution(Institution institution) throws  SQLException {
          boolean result = false;
          GenericBeanDAO gDB = new GenericBeanDAO();
          result = gDB.addBeanRelationship(this, institution);
          return result;
      }

6.2 Single Line/Multiple Lines Comments

For single line comments, we use //. The // can be used inside methods, inside classes, and for short declaration comment.

Example of single line comment:

    public boolean delete() throws  SQLException {
        // Right way.
        boolean result = false;
        GenericBeanDAO gDB = new GenericBeanDAO();
        // Course might have various institution relationships.
        for(Institution i : this.getInstitutions()){
            gDB.deleteBeanRelationship(this,i);
        }
        result = gDB.deleteBean(this);
        return result;
    }
    public boolean delete() throws  SQLException {
        /* WRONG WAY */
        boolean result = false;
        GenericBeanDAO gDB = new GenericBeanDAO();
        /* Course might have various institution relationships. */
        for(Institution i : this.getInstitutions()){
            gDB.deleteBeanRelationship(this,i);
        }
        result = gDB.deleteBean(this);
        return result;
    }

The /*...*/ single line comment is used only in if-else statements to show which one don't have an action.

If technical comments exceed one line they must be changed from '//' to /* & */, jumping a line to start and a line to finish.

Example of multiple lines comment:

    public ArrayList<Bean> runSql(Bean type, String sql) throws SQLException {
        this.openConnection();
        ArrayList<Bean> result = new ArrayList<Bean>();
        Cursor cs = this.database.rawQuery(sql, null);
        while (cs.moveToNext()) {
            Bean bean = init(type.identifier); 
            /* Represent an temporary generic Bean object that will be populated and added to the
            Arraylist beans */
            for (String s : type.fieldsList()) {
                bean.set(s, cs.getString(cs.getColumnIndex(s)));
            }
            result.add(bean);
        }
        this.closeConnection();
        return result;
    }

6.3 Statement Comments

When if / else statement have no action, leave a commentary like this.

Example 1:

public void set(String field, String data) {
    int dataIntFormat = Integer.parseInt(data);
    
    if (field.equals("_id")) {
        this.setId(dataIntFormat);
    } else if (field.equals("published_journals")) {
        this.setPublishedJournals(dataIntFormat);
    } else if (field.equals("published_conference_proceedings")) {
        this.setPublishedConferenceProceedings(dataIntFormat);
    } else {/* Nothing to do. */}
}

6.4 File Initial Comment

All source files should begin with a c-style comment that contains the file name, file extension, and a brief description of the purpose of the program with two sentences max. The comment syntax should beggin with thirty * and end with the same number of *. There should not be version control fields as 'Author', 'date' or 'version'.

Example:

/*****************************
 * Class name: Institution (.java)
 *
 * Purpose: Class that represents a generic institution entity. Stores the all data related to a
 * single institution.
 ****************************/

7. Keys & Indent:

7.1 General Rules

All keys must be in the same line of command. The value of a tab must be equivalent to 4 spaces. Every if statement shall have your else . If the latter does not take any action should be a comment, as specified in statement comments.

   // Correct way.
   for() {
       if() {
       } else if() {
       } else {
       }
   }
   // Wrong Way.
   for() {
       if() {
       } 
       else if() {
       } 
       else {
       }
   }

7.2 Blank Lines

The variable declarations and methods must be separated each by a blank line. Between the sentences package & import, must have a blank line. Between imports from different API's there must be a blank line.

package unb.mdsgpp.qualcurso;

import helpers.Indicator;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class IndicatorListAdapter extends ArrayAdapter<HashMap<String,String>> {
	
    public static String INDICATOR_VALUE = "indicatorValue";
    public static String VALUE = "value";
    private int itemLayout = 0;

    public IndicatorListAdapter(Context context, int resource, 
                                List<HashMap<String,String>> items) {
        ...

7.3 Blank Spaces

Each attribution, with the operator '=' must be followed with an unitary space before & after. In the use of a comma, there must be an empty space after. There must be space between the closing of parenthesis and method keys. In logical & arithmetic operations, there must be a blank space between the operators and operands.

    // Wrong.
    result= (Article)gDB.firstOrLastBean(result,false);
    // Right.
    result = (Article) gDB.firstOrLastBean(result, false);

7.4 Line Breakers

Instructions that break the line must be aligned with the operator '+' in the next line. In parameters, the line breaker (if necessary) must be after a comma.

// Wrong.
indicatorList.setAdapter(new IndicatorListAdapter(getActivity().getApplicationContext(),
                R.layout.evaluation_list_item, getListItems(evaluation))); 
// Right.
indicatorList.setAdapter(new IndicatorListAdapter(getActivity().getApplicationContext(),
                         R.layout.evaluation_list_item, getListItems(evaluation))); 

7.5 Annotations

Annotations should be written in previous line, see samples:

    // Correct way.
    @Override
    public void onAttach(Activity activity) {
        ...
    }

    // Wrong way.
    @Override public void onAttach(Activity activity){
        ...
    }

It should be used in any kind of annotation and any place.

8. Test

The name of the test classes must have "Test" followed by the name of the tested class.

   TestHospitalDao.java

The name of the methods must sugest the funcionality witch is being tested.

 @Test
    public void testGetPostalCode() {
        DrugStore drugStore = new DrugStore();
        drugStore.setPostalCode("2034");
        assertEquals("2034", drugStore.getPostalCode());
    }

9. Exceptions

When using resources for exception handling for the methods or logic & arithmetic expressions, these rules apply.

When you finish the 'try', must start in the same line with the 'catch' with a space of the end of one and the beginning of the other.

                try {
                    if(list != null){
                        rootView.setAdapter(new ArrayAdapter<Course>(
                        + getActionBar().getThemedContext(),
                        + R.layout.custom_textview, list));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }

When using "Throws" to pass the exception on to the next function in order to treat it, the method should look like this:

    public static int count() throws  SQLException {

10. Asserts

When creating assert one must verify parameters to avoid GIGO (garbage in, garbage out). Follow the patterns of the example:

   //Right
    public void setPublishedJournals(int publishedJournals) {
        assert (publishedJournals >= 0) : "publishedJournals must be positive";
        ...
    }
   
   // Wrong
    public void setPublishedJournals(int publishedJournals) {
        assert (publishedJournals >= 0);
        ...
    }

11. A Very Brief Example

/*
 * Class name: ResumedCodeConvention.java
 *
 * Purpose: Resume all Code Conventions.
 */

// Package of file.
package unb.mdsgpp.qualcurso;

// Android API imports.
import android.content.*;
import android.view.*;
import android.widget.*;

// Java API import.
import java.util.ArrayList;

// Project imports.
package unb.mdsgpp.qualcurso.R

/**
 * This is a class comment.
 * Describes something about class.
 */
public class ResumedCodeConvention {
    // ### First, the attributes of class. ###    
    
    // Hello! This is a single line comment!
    // Always initialize variables, lowerCammelCase, and pay attention on blank spaces.
    private String phraseExample = "";
    
    // This is an global variable. Name like this -> VARIABLE_NAME.
    public static final int MAX_VALUE = 10;


    // ### Constructor of class. ###
    public ResumedCodeConvention() {
        ...
    }

    
    // ### Methods of class. ###
    
    /*
     * Methods must be named in lowerCammelCase,
     * And needs a verb to describe the action he execute.
     *
     * Oh! By the way, this represents an MULTIPLE LINE COMMENT. 
     */
     public void getPhraseExample() {
         return phraseExample;
     }

     ...

     if(somethingHappened()) {
         // Example of unique usage of /* ... */ single line comment.
         /* ! Nothing To Do. */
     } else if() {
         ...
     } else {
         ...
     }
     
     
}