Skip to content

Android Coding Conventions

kevenzxd edited this page Feb 21, 2017 · 6 revisions

This is an ongoing documents, which we will continue to add contents.

  1. Base
  2. Improvement
  3. References

1. Base

1.1 Naming

Meaningful, For Short.

1.1.1 Fields

Non-constant field names (static or otherwise) are written in lowerCamelCase.

Fields should be defined at the top of the file and they should follow the naming rules listed below.

  • Private, non-static field names start with m.
  • Private, static field names start with s.
  • Other fields start with a lower case letter.
  • Static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.

Example:

public class MyClass {
    public static final int SOME_CONSTANT = 42;
    public int publicField;
    private static MyClass sSingleton;
    int mPackagePrivate;
    private int mPrivate;
    protected int mProtected;
}

1.1.2 Treat acronyms as words

Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
String url String URL
long id long ID

1.1.3 Constant Names

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. But what is a constant, exactly?

Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Merely intending to never mutate the object is not enough. Examples:

// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }

// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
    ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};

1.1.4 Local variable names

Local variable names are written in lowerCamelCase.

Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.

1.2 Format

1.3 Good Practice

2. Improvement

3. References

ADSDK 集成文档

Clone this wiki locally