Skip to content

Instantly share code, notes, and snippets.

@EhsanMashhadi
Last active June 28, 2018 13:30
Show Gist options
  • Save EhsanMashhadi/533d23203f326fc232df04af587e4e9f to your computer and use it in GitHub Desktop.
Save EhsanMashhadi/533d23203f326fc232df04af587e4e9f to your computer and use it in GitHub Desktop.
Android team's code convention

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.
  • For components in addition to the top rules,we use component+description.

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;
    private String mTitle;
    private TextView mTextViewTitle;
    private LinearLayout mLinearLayoutPhone;
    private Button mButtonSignIn;
}

Use standard brace style

Braces do not go on their own line; they go on the same line as the code before them:

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

We require braces around the statements for a conditional. Exception: If the entire conditional (the condition and the body) fit on one line, you may (but are not obligated to) put it all on one line. For example, this is acceptable:

if (condition) {
    body();
}

and this is acceptable:

if (condition) body();

but this is not acceptable:

if (condition)
    body();  // bad!

Treat acronyms as words

Treat acronyms and abbreviations as words in naming variables, methods, and classes to make names more readable:

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

Use TODO comments

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

// TODO: Remove this code after the UrlTable2 has been checked in.

and

// TODO: Change this to use a flag instead of a constant.

If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code after all production mixers understand protocol V7.").

Javatests style rules

Follow test method naming conventions and use an underscore to separate what is being tested from the specific case being tested. This style makes it easier to see exactly what cases are being tested. For example:

testMethod_specificCase1 testMethod_specificCase2

void testIsDistinguishable_protanopia() {
    ColorMatcher colorMatcher = new ColorMatcher(PROTANOPIA)
    assertFalse(colorMatcher.isDistinguishable(Color.RED, Color.BLACK))
    assertTrue(colorMatcher.isDistinguishable(Color.X, Color.Y))
}

Database name convention

Singular names for tables. Singular names for columns. Schema name for tables prefix (E.g.: SchemeName.TableName). Pascal casing (a.k.a. upper camel case). Example: FlightNumber

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

Resources

resourcenaming_cheatsheet

Layouts

Layouts are relatively simple, as there usually are only a few layouts per screen. Therefore the rule can be simplified to: layouts

Prefix Usage
activity contentview for activity
fragment view for a fragment
view inflated by a custom view
item layout used in list/recycler/gridview
layout layout reused using the include tag

Examples:

  • activity_main: content view of the MainActivity
  • fragment_articledetail: view for the ArticleDetailFragment
  • view_menu: layout inflated by custom view class MenuView
  • item_article: list item in ArticleRecyclerView
  • layout_actionbar_backbutton: layout for an actionbar with a backbutton (too simple to be a customview)

Strings

The <WHAT> part for Strings is irrelevant. So either we use <WHERE> to indicate where the string will be used: strings or all if the string is reused throughout the app: strings2

Examples:

  • articledetail_title: title of ArticleDetailFragment
  • feedback_explanation: feedback explanation in FeedbackFragment
  • feedback_namehint: hint of name field in FeedbackFragment
  • all_done: generic “done” string

<WHERE> obviously is the same for all resources in the same view.

Drawables

The <WHAT> part for Drawables is irrelevant. So either we use <WHERE> to indicate where the drawable will be used: drawables or all if the drawable is reused throughout the app: drawables2 Optionally you can add a <SIZE> argument, which can be an actual size “24dp” or a size qualifier “small”.

Examples:

  • articledetail_placeholder: placeholder in ArticleDetailFragment
  • all_infoicon: generic info icon
  • all_infoicon_large: large version of generic info icon
  • all_infoicon_24dp: 24dp version of generic info icon

IDs

For IDs, <WHAT> is the class name of the xml element it belongs to. Next is the screen the ID is in, followed by an optional description to distinguish similar elements in one screen. ids

Examples:

  • tablayout_main -> TabLayout in MainActivity
  • imageview_menu_profile -> profile image in custom MenuView
  • textview_articledetail_title -> title TextView in ArticleDetailFragment

Dimensions

Apps should only define a limited set of dimensions, which are constantly reused. This makes most dimensions all by default. Therefore you should mostly use: dimensions2 and optionally use the screen specific variant: dimensions Where <WHAT> is one of the following:

Prefix Usage
width width in dp
height height in dp
size if width == height
margin margin in dp
padding padding in dp
elevation elevation in dp
keyline absolute keyline measured from view edge in dp
textsize size of text in sp

Note that this list only contains the most used <WHAT>s. Other dimensions qualifiers like: rotation, scale,… are usually only used in drawables and as such less reused.

Examples:

  • height_toolbar: height of all toolbars
  • keyline_listtext: listitem text is aligned at this keyline
  • textsize_medium: medium size of all text
  • size_menu_icon: size of icons in menu
  • height_menu_profileimage: height of profile image in menu

reference :https://jeroenmols.com/blog/2016/03/07/resourcenaming/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment