Skip to content

Code style conventions

Olya Fomenko edited this page Mar 15, 2016 · 1 revision

1. Imports

Auto ordering to imports should be applied. This function available by default in Android Studio.

2. Package naming

General rule: com.companyname.projectname.directory.subdirectory. In case of complex project names, there can be two cases of package naming, for example:

  • com.mifos.mypackage.*
  • com.mifos.my_package.*

More preferable variant - without underscore. It is shorter and simplier.

3. File naming

3.1 Class naming

Class names are written in UpperCamelCase. For classes that extend an Android component, the name of the class should end with the name of the component; for example: ExampleActivity, ExampleFragment, ExampleService, ExampleDialog.

3.2 Resources files

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.

4. Code guidelines

4.1 Use access-modifiers

Always use access-modifiers (private, protected, public). Make public less data as possible. Use protected for all data, defined in parent and reused in all child classes. Use private for all data needed only in current class. Package private data access - bad solution for large packages, without sub-packages.

4.2 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 ExampleClass {
     public static final int INT_CONSTANT = 30;
     public static final String STRING_CONSTANT = “STRING_CONSTANT”;
     public int exampleFields;
     private static SingletonClass sSingleton;
     int mPackagePrivate;
     private int mPrivateField;
     protected int mProtectedField;
}

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

  • Constants
  • Fields
  • Constructors
  • Override methods and callbacks (public or private)
  • Public methods
  • Private methods
  • Inner classes or interfaces

4.4 Methods naming

Try to come up with meaningful method names that succinctly describe the purpose of the method, making your code self-documenting and reducing the need for additional comments. Compose method names using mixed case letters, beginning with a lowercase letter and starting each subsequent word with an uppercase letter.

Begin method names with a strong action verb (for example, deposit). If the verb is not descriptive enough by itself, include a noun (for example, addInterest). Add adjectives if necessary to clarify the noun (for example, convertDollarsToEuro).

Use the prefixes get and set for getter and setter methods. Getter methods merely return the value of a instance variable; setter methods change the value of a instance variable. For example, use the method names getBalance and setBalance to access or change the instance variable balance.

If the method returns a boolean value, use is or has as the prefix for the method name. For example, use isOverdrawn or hasCreditLeft for methods that return true or false values. Avoid the use of the word not in the boolean method name, use the ! operator instead.

For example, use !isOverdrawn instead of isNotOverdrawn.

4.5 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 go first
public User loadUser(Context context, int userId);
// Callbacks always go last
public void loadUserAsync(Context context, int userId, UserCallback callback);

4.6 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.

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 .

Bad code:

Picasso.with(context).load("image").into(imageView);

Good code:

Picasso.with(context)
        .load("image")
        .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 , Bad code:

loadPicture(context,”image”,mImageCompanyPicture, clickListener, "Picture title");

Good code:

loadPicture(context,
        "image",
        mImageCompanyPicture,
        clickListener,
        "Picture title");

4.7 Constants

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 indicaded below.

SharedPreferences - PREF_
Bundle - BUNDLE_
Fragment Arguments - ARG_
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 ARG_USER_ID = "ARG_USER_ID";
// Intent-related items use full package name as value
static final String EXTRA_NAME = "com.mifos.project.Const.EXTRA_NAME";
static final String ACTION_OPEN = "com.mifos.project.Const.ACTION_OPEN";

5. Resources naming

5.1 ID naming

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

TextView - tv_
ImageView - iv_
Button - btn_
Menu - menu_

5.2 Strings

String names start with a prefix that identifiers 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:

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"

5.3 Styles and Themes

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

5.4 Resources examples

Colors

<resources>
    <!-- basic colors -->
    <color name="green">#27D34D</color>
    <color name="blue">#2A91BD</color>
    <color name="orange">#FF9D2F</color>
    <color name="red">#FF432F</color>
</resources>

Dimens

<resources>
    <!-- font sizes -->
    <dimen name="font_larger">22sp</dimen>
    <dimen name="font_large">18sp</dimen>
    <dimen name="font_normal">14sp</dimen>
    <dimen name="font_small">12sp</dimen>
</resources>

Strings

<resources>
     <!-- error messages-->
     <string name="error_message_network">Network error</string>
     <string name="error_message_call">Call failed</string>
     <string name="error_message_map">Map loading failed</string>
</resources>