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:

Java

// This is Bad practice class myClass1 // This is good practice class MyClass <

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

Example:

Java

if (condition) < // 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:

Java

// 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:

Java

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

Handling Exceptions