-
Notifications
You must be signed in to change notification settings - Fork 0
Project Code Convention
Table of Contents
- Naming Files
- Classes
- Methods
- Attributes/Variables
- Line Length
- Comments
- Keys & Indent
- Test
- Exceptions
- Asserts
- A Very Brief Example
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:
- File Initial Comment
- Package
- Imports
- Class and it's methods.
Example:
/*****************************
* Class name: HospitalAdapter (.java)
*
* Purpose: Class that create an item list for the user by inflating the items and putting them on the
* screen.
*****************************/
package mds.gpp.saudeemcasa.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import mds.gpp.saudeemcasa.R;
import mds.gpp.saudeemcasa.model.Hospital;
public class HospitalAdapter extends ArrayAdapter<Hospital> {
private Context context = null;
private ArrayList<Hospital> list = null;
public static final int COUNT = 15;
public HospitalAdapter(Context context, ArrayList<Hospital> list){
super(context, 0, list);
this.context = context;
this.list = list;
}
...
}
The name of the classes must begin with capital letter in the singular, and must not be abbreviated. The following rules must be followed:
- Public classes must appear first in the class. Private should be last.
- 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 Stablishment {
private String latitude = "";
private String longitude = "";
private String type = "";
private String telephone = "";
private String name = "";
private String city = "";
private String address = "";
private String state = "";
private float rate = 0;
private String id;
private float distance = 0;
public Stablishment(String name, String telephone) {
this.name = name;
this.telephone = telephone;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
...
}
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 void onStatusChanged(String provider, int status, Bundle extras) {
...
}
Error messages must start with upper case and finish with finish dot. follow the pattern:
msgNeutralBuilder.setTitle("Falha na Conexão").setMessage("Não foi possível baixar os dados do servidor.");
Also parameters that are not modified during execution of method should be constant and defined "final" following the rules for constant declaration: NAME_NAME
Exemple:
public String updateRate(final int RATE, String ANDROID_ID, String HOSPITAL_ID){
...
}
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
- Contantes should also follow the pattern: NAME_NAME
Example of variables:
public class Stablishment {
// Correct way.
private String postalCode = "";
// Wrong Way
private String postalcode = "";
// Wrong Way
private String PostalCode = "";
// Wrong Way
private String POSTALcode = "";
}
Global variables examples:
public class HospitalAdapter extends ArrayAdapter<Hospital> {
...
// Correct way.
public static final int HOSPITAL_QUANTITY = 15;
// Wrong way
public static final int hospital_Quantity = 15;
// Wrong way
public static final int hOsPiTal_QuAnTiTy = 15;
...
}
Avoid lines longer than 80 characters. When a statement won't fill in a single line, it may be necessary to break it.
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.
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.
Example of Class comment:
/**
* Save or update rate from user on server database.
*
* @param RATE
* float value received from user input.
* @param ANDROID_ID
* string value that represents the unique android id.
* @param HOSPITAL_ID
* int value that represents the stablishment unique id.
*
* @return
* response from http connection.
*
* @throws ConnectionErrorException
* there maybe a problem connecting to server.
*/
public String updateRate(final int RATE, String ANDROID_ID, String HOSPITAL_ID)
throws ConnectionErrorException {
assert (RATE >= 0) : "minimum rate value interval.";
assert (RATE <= 5) : "maximum rate value interval.";
assert (ANDROID_ID != null) : "Null androidId treatment.";
assert (ANDROID_ID.length() > 2) : "Minor character androidId treatment.";
assert (HOSPITAL_ID != null) : "Nothing stored on hospitalId.";
assert (HOSPITAL_ID.length() >= 1) : "Verify hospitalId minor character.";
// Define ip address string.
HttpConnection connection = new HttpConnection();
final String SERVER_IP_ADDRESS = "http://159.203.95.153:3000/rate/gid/";
final String IP_ADDRESS_WITH_ANDROID_ID = SERVER_IP_ADDRESS + HOSPITAL_ID + "/aid/"
+ ANDROID_ID;
final String IP_ADDRESS_WITH_RATING = IP_ADDRESS_WITH_ANDROID_ID + "/rating/" + RATE;
// Make request.
final String RESPONSE_WITH_RATES = connection.newRequest(IP_ADDRESS_WITH_RATING);
return RESPONSE_WITH_RATES;
}
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 void requestRating() throws ConnectionErrorException {
// Correct way.
HttpConnection httpConnection = new HttpConnection(); // New Connection.
}
public void requestRating() throws ConnectionErrorException {
/* WRONG WAY TO COMMENT */
HttpConnection httpConnection = new HttpConnection(); /* New Connection */.
}
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:
/*
* Return the unique instance of DrugstoreController active in the project, in order to
* not have multiple at the same time.
*/
return instance;
}
When if
/ else
statement have no action, leave a commentary like this.
Example 1:
if(DrugStoreDao.instance != null) {
/*Nothing To Do.*/
} else {
DrugStoreDao.instance = new DrugStoreDao( context );
}
Example 2:
if (drugstoreController.getAllDrugstores().size()>0 &&
hospitalController.getAllHospitals().size()>0) {
toListScreen();
} else {
/*Nothing To Do.*/
}
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 * following the exemple:
/*****************************
* Class name: Hospital (.java)
*
* Purpose: Represents a generic hospital entity. Stores the data
* that characterize the hospital organization.
****************************/
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.
if(gps.canGetLocation()) {
double userLongitude = gps.getLongitude();
double userLatitude = gps.getLatitude();
for(int i = 0; i < list.size(); i++) {
...
}
sort(list, new DistanceComparator());
return true;
} else {
return false;
}
// Wrong Way.
if ( gps.canGetLocation() == true)
{
double userLongitude = gps.getLongitude();
double userLatitude = gps.getLatitude();
for ( int i = 0; i < list.size(); i++ ) {
...
}
sort(list, new DistanceComparator());
return true;
}
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 mds.gpp.saudeemcasa.view;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import mds.gpp.saudeemcasa.R;
import mds.gpp.saudeemcasa.controller.DrugStoreController;
public class GoogleMapDrugStore extends FragmentActivity {
private GoogleMap mMap;
DrugStoreController controller = DrugStoreController.getInstance(this);
@Override
protected void onCreate(Bundle savedInstanceState)
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.
// Correct Way.
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
public Location getLocation() {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
...
}
// Wrong Way.
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
public Location getLocation(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
...
}
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.
// Correct Way.
String jsonPrivate = httpConnectionPrivate.RequestAllDrugstoresByUF("http://159." +
"203.95.153:3000/farmacia_popular_conveniada");
// Wrong Way.
textViewDistance.setText(convertToKM(this.lista.get(position).getDistance()).toString() + " Km");
Annotations should be written in previous line, see samples:
// Correct way.
@Override
public int getCount() {
...
}
// Wrong way.
@Override public int getCount() {
...
}
It should be used in any kind of annotation and any place.
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());
}
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 {
hospitalController.initControllerHospital();
} catch (ConnectionErrorException failedConnection) {
showMessageOnThread(messageFailedConnection, messageHandler);
}
When using "Throws" to pass the exception on to the next function in order to treat it, the method should look like this:
public void initControllerHospital() throws ConnectionErrorException {
When creating assert one must verify parameters to avoid GIGO (garbage in, garbage out). Follow the patterns of the example:
// Wrong
public boolean insertDrugstore(DrugStore drugStore) {
assert(drugStore != null);
...
}
// Right
public boolean insertDrugstore(DrugStore drugStore) {
assert (drugStore != null) : "drugStore object must never be null";
...
}
/***********************************
* Class name: ResumedCodeConvention (.java)
*
* Purpose: Resume all Code Conventions.
***********************************/
// Package of file.
package mds.gpp.saudeemcasa.sample;
// Android API imports.
import android.content.*;
import android.view.*;
import android.widget.*;
// Java API import.
import java.util.ArrayList;
// Project imports.
import mds.gpp.saudeemcasa.R;
/**
* This is a class comment.
* Describes something about class.
*/
public class ResumedCodeConvention {
// 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;
public ResumedCodeConvention() {
...
}
/*
* 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 {
...
}
}