Open In App

Android Coding Style and Guidelines

While you writing code, there are some rules you need to follow to keep code easy to read and clean. If you are not new to coding, you probably already know about coding standards. Coding standards vary from person to person and can be different for different projects. Before starting adding or updating code in someone else’s project or open source project, you should first look around to identify the coding style they’ve used and try to follow the same. Here are some commonly accepted coding standards for android which will help you to write clean code.

Standard Coding Style to Follow

1. Indent your code Properly with tabs or 4 white spaces.



2. Put braces on the same line as the code before them, not on their own line.

Example:






// This is Bad practice
class myClass1
{
  int func2()
  {
    //...
  }
}
 
// This is good practice
class MyClass {
    int func() {
        if(){
            //...
        }else{
            //...
        }
    }
}

3. If the condition and the body fit on one line, you may put it all on one line.

Example:




if (condition) {
    body();
}
 
// can be written as
if(condition) body();
 
// But not like
if(condition)
    body(); // Bad Practice

4. Use TODO comments for code that is temporary, a short-term solution, or good enough but not perfect. These comments should include the string “TODO” in all caps, followed by a colon.

Example:




// TODO: Use boolean Flag instead of int constant.

5. Switch case should always have a “default” statement to catch unexpected values.

6. Use standard predefined annotations in code wherever needed.

Example:




@Deprecated
// used to mark component which no longer should be used.
 
@Override
// used to tell that declared method overrides method in superclass.
 
@Nullable
// tells that parameter, return value of method or field can be null.
 
@NonNull
// tells that parameter, return value of method or field can not be null.

Handling Exceptions

Loops

Example: Declare iteration variable in for loop itself.




int i = 0;
 
// bad practice
for(i= 0; i< 10; i++)
   
// Good practice
for(int i=0; i<10; i++){
    // do your work
}
 
// good practice
for(Iterator i = c.iterator(); i.hasNext()){
    // do your work
}

Standard Naming Rules to Follow

Naming conventions in coding:

Naming conventions in XML:

Handling Resources 

All resources that are being used in the project should be defined in the “res” folder of the application in the following format:


Article Tags :