Skip to content

Instantly share code, notes, and snippets.

@ianngiaw
Last active January 17, 2017 05:19
Show Gist options
  • Save ianngiaw/f0188c7ec3dff232545d6ed263c99e03 to your computer and use it in GitHub Desktop.
Save ianngiaw/f0188c7ec3dff232545d6ed263c99e03 to your computer and use it in GitHub Desktop.

Android coding style

File Naming Style

Class Names

UpperCamelCase

Superclass at back for native android components

EmailWebView, EmailListActivity...

Icons Resources

All icon resources should start with ic_.

Other Image resources

Start with the package the name it is used in

emaildetail_background, composer_recipient_border

If the resource is being in multiple packages, set the prefix as the lowest common parent package.

i.e.

ui
|-- emaillist
|   +-- EmailListFragment
+-- composer
    +-- ComposeActivity

If a resource is used in both EmailListFragment and ComposeActivity, then its prefix should be ui_.

Layout Resources

Layout files should match the name of the Android components that they are intended for but moving the top level component name to the beginning. For example, if we are creating a layout for the SignInActivity, the name of the layout file should be activity_sign_in.xml.

Component Class Name Layout Name
Activity UserProfileActivity activity_user_profile.xml
Fragment SignUpFragment fragment_sign_up.xml
Dialog ChangePasswordDialog dialog_change_password.xml
AdapterView item --- item_person.xml
Partial layout --- partial_stats_bar.xml

A slightly different case is when we are creating a layout that is going to be inflated by an Adapter, e.g to populate a ListView. In this case, the name of the layout should start with item_.

Note that there are cases where these rules will not be possible to apply. For example, when creating layout files that are intended to be part of other layouts. In this case you should use the prefix partial_.

Menu files

Similar to layout files, menu files should match the name of the component. For example, if we are defining a menu file that is going to be used in the UserActivity, then the name of the file should be activity_user.xml

A good practice is to not include the word menu as part of the name because these files are already located in the menu directory.

Values files

Resource files in the values folder should be plural, e.g. strings.xml, styles.xml, colors.xml, dimens.xml, attrs.xml

Coding Style

@Nullables

Use the @Nullable annotation whenever a null can be expected.

For variables,

class A {
    @Nullable Object b;
}

For methods,

class A {
    @Nullable
    Object foo() {
        return null;
    }
}

For parameters,

class A {
    void foo(@Nullable Object b) {
        ...
    }
}

Similarly, use the @NonNull annotation whenever no nulls are expected.

class A {
    void foo(@NonNull Object b) {
        ...
    }
}

For methods,

class A {
    @NonNull
    Object foo() {
        return new Object(); // Cannot be null
    }
}

For parameters,

class A {
    void foo(@NonNull Object b) { // b cannot be null
        ...
    }
}

Exceptions

Always handle all your exceptions

Avoid throwing to caller at all costs. Try to handle exceptions using notifications.

Don't catch generic exceptions

try {
    someComplicatedIOFunction();        // may throw IOException
    someComplicatedParsingFunction();   // may throw ParsingException
    someComplicatedSecurityFunction();  // may throw SecurityException
    // phew, made it all the way
} catch (Exception e) {                 // I'll just catch all exceptions
    handleError();                      // with one generic handler!
}

Don't use finalizers

Either use native Android lifecycle methods or exception handling.

Fully qualify imports

This is bad: import foo.*;

This is good: import foo.Bar;

Java Coding Style

Fields definition and naming

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;
}

Treat acronyms as words

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

Use spaces for indentation

Use 4 space indents for blocks:

if (x == 1) {
    x++;
}

Use 8 space indents for line wraps:

Instrument i =
        someLongExpression(that, wouldNotFit, on, one, line);

Use standard brace style

Braces go on the same line as the code before them.

class MyClass {
    int func() {
        if (something) {
            // ...
        } else if (somethingElse) {
            // ...
        } else {
            // ...
        }
    }
}

Do not use single line if statements

Bad

if (condition) doFunc();

Good

if (condition) {
  doFunc();
}

Annotations practices

According to the Android code style guide, the standard practices for some of the predefined annotations in Java are:

  • @Override: The @Override annotation must be used whenever a method overrides the declaration or implementation from a super-class. For example, if you use the @inheritdocs Javadoc tag, and derive from a class (not an interface), you must also annotate that the method @Overrides the parent class's method.

  • @SuppressWarnings: The @SuppressWarnings annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to ensure that all warnings reflect actual problems in the code.

Annotations style

Classes, Methods and Constructors

When annotations are applied to a class, method, or constructor, they are listed after the documentation block and should appear as one annotation per line .

/* This is the documentation block about the class */
@AnnotationA
@AnnotationB
public class MyAnnotatedClass { }

Fields

Annotations applying to fields should be listed on the same line, unless the line reaches the maximum line length.

@Nullable @Mock DataManager mDataManager;

Logging guidelines

Use the logging methods provided by the Log class to print out error messages or other information that may be useful for developers to identify issues:

  • Log.v(String tag, String msg) (verbose)
  • Log.d(String tag, String msg) (debug)
  • Log.i(String tag, String msg) (information)
  • Log.w(String tag, String msg) (warning)
  • Log.e(String tag, String msg) (error)

As a general rule, we use the class name as tag and we define it as a static final field at the top of the file. For example:

public class MyClass {
    private static final String TAG = MyClass.class.getSimpleName();

    public myMethod() {
        Log.e(TAG, "My error message");
    }
}

VERBOSE and DEBUG logs must be disabled on release builds. It is also recommended to disable INFORMATION, WARNING and ERROR logs but you may want to keep them enabled if you think they may be useful to identify issues on release builds. If you decide to leave them enabled, you have to make sure that they are not leaking private information such as email addresses, user ids, etc.

To only show logs on debug builds:

if (BuildConfig.DEBUG) Log.d(TAG, "The value of x is " + x);

Class member ordering

There is no single correct solution for this but using a logical and consistent order will improve code learnability and readability. It is recommendable to use the following order:

  1. Constants
  2. Fields
  3. Constructors
  4. Override methods and callbacks (public or private)
  5. Public methods
  6. Private methods
  7. Inner classes or interfaces

Example:

public class MainActivity extends Activity {

	private String mTitle;
    private TextView mTextViewTitle;

    public void setTitle(String title) {
    	mTitle = title;
    }

    @Override
    public void onCreate() {
        ...
    }

    private void setUpView() {
        ...
    }

    static class AnInnerClass {

    }

}

If your class is extending an Android component such as an Activity or a Fragment, it is a good practice to order the override methods so that they match the component's lifecycle. For example, if you have an Activity that implements onCreate(), onDestroy(), onPause() and onResume(), then the correct order is:

public class MainActivity extends Activity {

	//Order matches Activity lifecycle
    @Override
    public void onCreate() {}

    @Override
    public void onResume() {}

    @Override
    public void onPause() {}

    @Override
    public void onDestroy() {}

}

Parameter ordering in methods

When programming for Android, it is quite common to define methods that take a Context. If you are writing a method like this, then the Context must be the first parameter.

The opposite case are callback interfaces that should always be the last parameter.

Examples:

// Context always goes first
public User loadUser(Context context, int userId);

// Callbacks always go last
public void loadUserAsync(Context context, int userId, UserCallback callback);

String constants, naming, and values

Many elements of the Android SDK such as SharedPreferences, Bundle, or Intent use a key-value pair approach so it's very likely that even for a small app you end up having to write a lot of String constants.

When using one of these components, you must define the keys as a static final fields and they should be prefixed as indicated below.

Element Field Name Prefix
SharedPreferences PREF_
Bundle BUNDLE_
Fragment Arguments ARGUMENT_
Intent Extra EXTRA_
Intent Action ACTION_

Note that the arguments of a Fragment - Fragment.getArguments() - are also a Bundle. However, because this is a quite common use of Bundles, we define a different prefix for them.

Example:

// Note the value of the field is the same as the name to avoid duplication issues
static final String PREF_EMAIL = "PREF_EMAIL";
static final String BUNDLE_AGE = "BUNDLE_AGE";
static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID";

// Intent-related items use full package name as value
static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME";
static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER";

Arguments in Fragments and Activities

When data is passed into an Activity or Fragment via an Intent or a Bundle, the keys for the different values must follow the rules described in the section above.

When an Activity or Fragment expects arguments, it should provide a public static method that facilitates the creation of the relevant Intent or Fragment.

In the case of Activities the method is usually called getStartIntent():

public static Intent getStartIntent(Context context, User user) {
	Intent intent = new Intent(context, ThisActivity.class);
	intent.putParcelableExtra(EXTRA_USER, user);
	return intent;
}

For Fragments it is named newInstance() and handles the creation of the Fragment with the right arguments:

public static UserFragment newInstance(User user) {
	UserFragment fragment = new UserFragment;
	Bundle args = new Bundle();
	args.putParcelable(ARGUMENT_USER, user);
	fragment.setArguments(args)
	return fragment;
}

Line length limit

Code lines should not exceed 100 characters. If the line is longer than this limit there are usually two options to reduce its length:

  • Extract a local variable or method (preferable).
  • Apply line-wrapping to divide a single line into multiple ones.

There are two exceptions where it is possible to have lines longer than 100:

  • Lines that are not possible to split, e.g. long URLs in comments.
  • package and import statements.

Line-wrapping strategies

There isn't an exact formula that explains how to line-wrap and quite often different solutions are valid. However there are a few rules that can be applied to common cases.

Break at operators

When the line is broken at an operator, the break comes before the operator. For example:

int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
        + theFinalOne;

Assignment Operator Exception

An exception to the break at operators rule is the assignment operator =, where the line break should happen after the operator.

int longName =
        anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne;

Method chain case

When multiple methods are chained in the same line - for example when using Builders - every call to a method should go in its own line, breaking the line before the .

Picasso.with(context).load("http://ribot.co.uk/images/sexyjoe.jpg").into(imageView);
Picasso.with(context)
        .load("http://ribot.co.uk/images/sexyjoe.jpg")
        .into(imageView);

Long parameters case

When a method has many parameters or its parameters are very long, we should break the line after every comma ,

loadPicture(context, "http://ribot.co.uk/images/sexyjoe.jpg", mImageViewProfilePicture, clickListener, "Title of the picture");
loadPicture(context,
        "http://ribot.co.uk/images/sexyjoe.jpg",
        mImageViewProfilePicture,
        clickListener,
        "Title of the picture");

XML Style Rules

Use self closing tags

When an XML element doesn't have any contents, you must use self closing tags.

This is good:

<TextView
	android:id="@+id/text_profile"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content" />

This is bad :

<!-- Don\'t do this! -->
<TextView
    android:id="@+id/text_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>

Resources naming

Resource IDs and names are written in lowercase_underscore.

ID naming

IDs should be prefixed with the name of the element in lowercase underscore. For example:

Element Prefix
TextView text_
ImageView image_
Button button_
Menu menu_

Image view example:

<ImageView
    android:id="@+id/image_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Menu example:

<menu>
	<item
        android:id="@+id/menu_done"
        android:title="Done" />
</menu>

Strings

String names start with a prefix that identifies the section they belong to. For example registration_email_hint or registration_name_hint. If a string doesn't belong to any section, then you should follow the rules below:

Prefix Description
error_ An error message
msg_ A regular information message
title_ A title, i.e. a dialog title
action_ An action such as "Save" or "Create"

Styles and Themes

Unless the rest of resources, style names are written in UpperCamelCase.

Attributes ordering

As a general rule you should try to group similar attributes together. A good way of ordering the most common attributes is:

  1. View Id
  2. Layout width and layout height
  3. Style
  4. Other layout attributes, sorted alphabetically
  5. Remaining attributes, sorted alphabetically

Tests style rules

Unit tests

Test classes should match the name of the class the tests are targeting, followed by Test. For example, if we create a test class that contains tests for the DatabaseHelper, we should name it DatabaseHelperTest.

Test methods are annotated with @Test and should generally start with the name of the method that is being tested, followed by a precondition and/or expected behaviour.

  • Template: @Test void methodNamePreconditionExpectedBehaviour()
  • Example: @Test void signInWithEmptyEmailFails()

Precondition and/or expected behaviour may not always be required if the test is clear enough without them.

Sometimes a class may contain a large amount of methods, that at the same time require several tests for each method. In this case, it's recommendable to split up the test class into multiple ones. For example, if the DataManager contains a lot of methods we may want to divide it into DataManagerSignInTest, DataManagerLoadUsersTest, etc. Generally you will be able to see what tests belong together because they have common test fixtures.

Espresso tests

Every Espresso test class usually targets an Activity, therefore the name should match the name of the targeted Activity followed by Test, e.g. SignInActivityTest

When using the Espresso API it is a common practice to place chained methods in new lines.

onView(withId(R.id.view))
        .perform(scrollTo())
        .check(matches(isDisplayed()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment