- Android Coding Style and Guidelines
- Standard Coding Style to Follow
- Handling Exceptions
- Loops
- Standard Naming Rules to Follow
- 7 reasons this Android Code Style improves your productivity
- At grandcentrix we use the same code style in all Android projects and we love it! We open sourced it so you can use it, too.
- grandcentrix/AndroidCodeStyle
- AndroidCodeStyle — Android code style settings for Android Studio at grandcentrix
- 1. You finally have a code style
- 2. Awesome features
- 3. Conservative style and updates
- 4. Not Square
- 5. No additional tool required
- 6. Easy to install
- 7. Reformat on save
- Try it!
- Coding style in android
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:
3. If the condition and the body fit on one line, you may put it all on one line.
Example:
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:
5. Switch case should always have a “default” statement to catch unexpected values.
6. Use standard predefined annotations in code wherever needed.
Example:
Handling Exceptions
- You should never leave your catch block empty, even if you are too sure that exception will never occur.
- Try to catch exceptions separately, do not catch generic exceptions.
- Try to use different “try” blocks for statements that can cause different exceptions. Ex.- separate parsing statements from Input statements into separate “try” blocks.
- If you are confident about ignoring exceptions, then you should put an appropriate comment explaining why exceptions can be ignored,
Loops
Example: Declare iteration variable in for loop itself.
Standard Naming Rules to Follow
Naming conventions in coding:
- Non-static, Non-public (i.e., private, default, and protected) field names should start with m, Ex.- int mVar.
- Static field names should start with s, Ex.- private static int sVar.
- Public fields should start with a lower case letter, Ex.- public int var.
- Public static final fields or constants should be in all caps with underscores, Ex.- public static final int MY_CONSTANT = 42.
- Class or interface name should always start with a capital letter and the first letter of the changing word should be also in capital Ex.- MyClass, MyInterface, MyCustomViewClass
- The class should have comments at the top which clearly state the purpose of the class creation. Same for functions.
- The function name should always start with a small letter, and the first letter of the changing word should be capitalized. Ex.- public int registeNewUser(),
Naming conventions in XML:
- Layout files should match the name of the Android components that they are intended. Ex.- layout file for LoginActivity.class should be nam
- ed as activity_login.xml.
- When we are creating a layout that is going to be inflated by an Adapter, i.e., to populate a ListView or RecyclerView. In this case, the name of the layout should start with “item_”, Ex.- item_contact_card.xml.
- Layout resource id should use the naming convention where possible: _ _ , Ex.- profile_imageview_avatar.
- When defining string in strings.xml, name of string should follow this syntax:
_ , Ex.- Enter your login ID .
Drawable files should be named as
Источник
7 reasons this Android Code Style improves your productivity
At grandcentrix we use the same code style in all Android projects and we love it! We open sourced it so you can use it, too.
Oct 5, 2017 · 5 min read
We’ve started with the AOSP Java Code Style and tuned it depending on our needs over the last years. Due to official support of Kotlin we knew we have to create a major update. We’ve took the chance and went even further by questioning old decisions in an internal survey and adding long awaited features. The result is a code style 20+ Android developers at grandcentrix agree on. By publishing it to the public you and your team can benefit from it, too!
grandcentrix/AndroidCodeStyle
AndroidCodeStyle — Android code style settings for Android Studio at grandcentrix
Why you should definitely try this code style? Let me explain:
1. You finally have a code style
You mi g ht ask yourself why you need a code style. When you are used working alone on your apps you don’t have problems with your personal manual code formatting. Discussions start when multiple developers, with multiple opinions, multiple operating systems and multiple screen sizes work on the same code base. If you don’t let a tool format your code, discussions about the formatting may arise or worse, different formatting and sorting increases diffs and can causes completely unnecessary merge conflicts. This will slow down development for no reason.
Discuss problems, not formatting.
Even when working alone it’s unprofessional not to have a common formatting throughout your project. It means your project is not ready to scale to two or more developers.
It’s a good start if you use Android Studios default code formatting. But that’s unsafe! The default settings have changed in the past and will change in the future. Your team should use a code style independent from the IntelliJ version one is working on.
2. Awesome features
What makes this code style different? Here’s a short list of key features we’ve added or kept compared to the AOSP code style. Detailed information about each feature can be found in our Android Code Style repository on GitHub.
3. Conservative style and updates
Over the time our Android team requested new rules for the code style. Instead of adding every request we collected them and created a survey about each feature of this code style; existing rules as well as new requests. If most devs agree on we tried to add it. If rules are to specific for a project/framework/library they won’t be added.
This democratic principle makes sure all of our 20+ developers are happy with the code style. Not everyone may agree with all rules, but most developers in our team agree with most rules. Chances are good most members of your team also agree on our code style. Try it!
4. Not Square
We could have chosen an already existing code style such as Squares Java code style which you might know from various open source projects. This style is different and has some rules we don’t like such as annotations in the same line as the method definition or reducing the indents to 2 spaces.
Those radical style changes compared to the “normal Java style” we are used to did not receive much love by our developers. It’s completely subjective but one of the reasons why we wanted to publish our own code style, reflecting our own opinions.
If you are searching for a code style for your open source library and you don’t like Square ones, here is a possible alternative.
5. No additional tool required
When we talk about code style we have to mention checkstyle. If you’re using it, fine. For us, the Android Studio formatter is enough. Everybody is using Android Studio and it works on all platforms. No additional tool is required which can break and requires maintenance.
6. Easy to install
Even though we’re not using Squares code style we copied their script to copy the code style to all IntelliJ/Android Studio IDEs you have installed by running ./install.sh . Thanks Square Engineering for open sourcing it.
- git clone git@github.com:grandcentrix/AndroidCodeStyle.git
- cd AndroidCodeStyle
- ./install.sh
- Restart Android Studio
- Select the code style scheme via Preferences —> Editor —> Code Style
7. Reformat on save
With 3 simple steps you can reorder and reformat your code automatically with ⌘ + S. That shortcut you are used to press constantly although you know Android Studio automatically saves all files for you . Give ⌘ + S a different meaning:
- Make sure a Java source file has focus (or you can’t record all steps)
- — Select Edit > Macros > Start Macro Recording
— Select Code > Optimize Imports
— Select Code > Reformat Code
— Select Code > Rearrange Code
— Select File > Save All
— Select Edit > Macros > Stop Macro Recording and give it a name (mine is OptimizeImportsReformatRearrangeSave ) - Go to Preferences > Keymap
— Find the Macro section
— Add ⌘ + S shortcut for the new macro
Alternatively you can reformat code with ⌥+⌘+L . When you select parts of your code, only those get reformatted. This doesn’t reorder your code or changes imports. I use it when touching code which doesn’t have a code style.
Try it!
We’d like to know what you think about our code style. Tweet us your honest feedback or open issues in our repository.
Источник
Coding style in android
1. Project guidelines
1.1 Project structure
New projects should follow the Android Gradle project structure that is defined on the Android Gradle plugin user guide. The ribot Boilerplate project is a good reference to start from.
1.2.1 Class files
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: SignInActivity , SignInFragment , ImageUploaderService , ChangePasswordDialog .
1.2.2 Resources files
Resources file names are written in lowercase_underscore.
1.2.2.1 Drawable files
Naming conventions for drawables:
Asset Type | Prefix | Example |
---|---|---|
Action bar | ab_ | ab_stacked.9.png |
Button | btn_ | btn_send_pressed.9.png |
Dialog | dialog_ | dialog_top.9.png |
Divider | divider_ | divider_horizontal.9.png |
Icon | ic_ | ic_star.png |
Menu | menu_ | menu_submenu_bg.9.png |
Notification | notification_ | notification_bg.9.png |
Tabs | tab_ | tab_pressed.9.png |
Naming conventions for icons (taken from Android iconography guidelines):
Asset Type | Prefix | Example |
---|---|---|
Icons | ic_ | ic_star.png |
Launcher icons | ic_launcher | ic_launcher_calendar.png |
Menu icons and Action Bar icons | ic_menu | ic_menu_archive.png |
Status bar icons | ic_stat_notify | ic_stat_notify_msg.png |
Tab icons | ic_tab | ic_tab_recent.png |
Dialog icons | ic_dialog | ic_dialog_info.png |
Naming conventions for selector states:
State | Suffix | Example |
---|---|---|
Normal | _normal | btn_order_normal.9.png |
Pressed | _pressed | btn_order_pressed.9.png |
Focused | _focused | btn_order_focused.9.png |
Disabled | _disabled | btn_order_disabled.9.png |
Selected | _selected | btn_order_selected.9.png |
1.2.2.2 Layout 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 .
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_ .
1.2.2.3 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.
1.2.2.4 Values files
Resource files in the values folder should be plural, e.g. strings.xml , styles.xml , colors.xml , dimens.xml , attrs.xml
2 Code guidelines
2.1 Java language rules
2.1.1 Don’t ignore exceptions
You must never do the following:
While you may think that your code will never encounter this error condition or that it is not important to handle it, ignoring exceptions like above creates mines in your code for someone else to trip over some day. You must handle every Exception in your code in some principled way. The specific handling varies depending on the case. — (Android code style guidelines)
2.1.2 Don’t catch generic exception
You should not do this:
See the reason why and some alternatives here
2.1.3 Don’t use finalizers
We don’t use finalizers. There are no guarantees as to when a finalizer will be called, or even that it will be called at all. In most cases, you can do what you need from a finalizer with good exception handling. If you absolutely need it, define a close() method (or the like) and document exactly when that method needs to be called. See InputStream for an example. In this case it is appropriate but not required to print a short log message from the finalizer, as long as it is not expected to flood the logs. — (Android code style guidelines)
2.1.4 Fully qualify imports
This is bad: import foo.*;
This is good: import foo.Bar;
2.2 Java style rules
2.2.1 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.
2.2.3 Treat acronyms as words
Good | Bad |
---|---|
XmlHttpRequest | XMLHTTPRequest |
getCustomerId | getCustomerID |
String url | String URL |
long id | long ID |
2.2.4 Use spaces for indentation
Use 4 space indents for blocks:
Use 8 space indents for line wraps:
2.2.5 Use standard brace style
Braces go on the same line as the code before them.
Braces around the statements are required unless the condition and the body fit on one line.
If the condition and the body fit on one line and that line is shorter than the max line length, then braces are not required, e.g.
This is bad:
2.2.6.1 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.
More information about annotation guidelines can be found here.
2.2.6.2 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 .
Fields
Annotations applying to fields should be listed on the same line, unless the line reaches the maximum line length.
2.2.7 Limit variable scope
The scope of local variables should be kept to a minimum (Effective Java Item 29). By doing so, you increase the readability and maintainability of your code and reduce the likelihood of error. Each variable should be declared in the innermost block that encloses all uses of the variable.
Local variables should be declared at the point they are first used. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do. — (Android code style guidelines)
2.2.8 Order import statements
If you are using an IDE such as Android Studio, you don’t have to worry about this because your IDE is already obeying these rules. If not, have a look below.
The ordering of import statements is:
- Android imports
- Imports from third parties (com, junit, net, org)
- java and javax
- Same project imports
To exactly match the IDE settings, the imports should be:
- Alphabetically ordered within each grouping, with capital letters before lower case letters (e.g. Z before a).
- There should be a blank line between each major grouping (android, com, junit, net, org, java, javax).
2.2.9 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:
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:
2.2.10 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
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:
2.2.11 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.
2.2.13 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.
2.2.14 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() :
For Fragments it is named newInstance() and handles the creation of the Fragment with the right arguments:
Note 1: These methods should go at the top of the class before onCreate() .
Note 2: If we provide the methods described above, the keys for extras and arguments should be private because there is not need for them to be exposed outside the class.
2.2.15 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.
2.2.15.1 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:
Assignment Operator Exception
An exception to the break at operators rule is the assignment operator = , where the line break should happen after the operator.
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 .
Long parameters case
When a method has many parameters or its parameters are very long, we should break the line after every comma ,
2.2.16 RxJava chains styling
Rx chains of operators require line-wrapping. Every operator must go in a new line and the line should be broken before the .
2.3 XML style rules
2.3.1 Use self closing tags
When an XML element doesn’t have any contents, you must use self closing tags.
This is bad :
2.3.2 Resources naming
Resource IDs and names are written in lowercase_underscore.
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:
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» |
2.3.2.3 Styles and Themes
Unlike the rest of resources, style names are written in UpperCamelCase.
2.3.3 Attributes ordering
As a general rule you should try to group similar attributes together. A good way of ordering the most common attributes is:
- View Id
- Style
- Layout width and layout height
- Other layout attributes, sorted alphabetically
- Remaining attributes, sorted alphabetically
2.4 Tests style rules
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.
2.4.2 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.
Источник