MOBILOITTTE - ANDROID+KOTLIN-Coding Guidelines
MOBILOITTTE - ANDROID+KOTLIN-Coding Guidelines
MOBILOITTTE - ANDROID+KOTLIN-Coding Guidelines
1 Java language
rules
void setServerPort(String
value) {
} catch
(NumberFormatException e)
{}
}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)
See alternatives
here.
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 InputStreamfor 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 Java style
rules
Fields should be defined at the top of the file and they should follow the
naming rules listed below.
Exampl
e:
public
class
MyClas
s{
public
static final
intSOME_CONSTANT
=42;public int
publicField;
private static
MyClass sSingleton;
int
mPackagePrivat
e;
private int
mPrivate;
protected
int
mProtected
;
Good Bad
XmlHttpRequest
XMLHTTPRequest
getCustomerId
getCustomerID
long id long ID
if (x
== 1)
{x++;
}
Use 8 space indents for line
wraps:
Instrument
i=
someLongExpression(that, wouldNotFit,
on, one, line);
class
MyClas
s{
int
func(
){
if
(something)
{
/ ..
.
} else if
(somethingEls
e) {
/ ..
.
} else
{
/ ..
.
}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.
if (condition)
body();
This is
bad:
if
(condition
)
body(); //
bad!
2.5
Annotations
2.5.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.
2.5.2 Annotations
style
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 */
@Annotati
onA
@Annotati
onB
public class
MyAnnotatedCla
ss { }
Field
s
Annotations applying to fields should be listed on the same line, unless the line reaches the
maximum line length.
@Nullable @Mock
DataManager mDataManager;
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)
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.
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).
More info
here
2.8 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:
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
MyClas
s{
public
myMethod
() {
}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.
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:
Exampl
e:
public
class
MainActi
vity
extends
Activity {
private String
mTitle;
private TextView
mTextViewTitle;
public
void
setTitle(String
title) {
mTitle =
title;
}@Override
p
ublic void
onCreate
() {
..
.
}
void
private
setUpView
() {
..
.
}
static
class
AnInnerCla
ss {
}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
MainActi
vity
extends
Activity {
@Overri
de
pu
blic void
onCreate(
) {}
@Overri
de
pub
lic void
onResume
() {}
@Overri
de
pu
blic void
onPause(
) {}
@Overri
de
pu
blic void
onDestroy(
) {}
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.
Exampl
es:
// Context always
goes first
public User loadUser(Context context,
int userId);
// Callbacks always
go last
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.
Bundle BUNDLE_
Fragment Arguments
ARGUMENT_
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.
Exampl
e:
// Note the value of the field is the same as the name to avoid
duplication issues
When data is passed into an Activityor 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 Frag ment.
intent.putParcelableExtra(EXTRA_US
ER, user);
return
intent;
}For Fragments it is named newInstance() and handles the creation of the Fragment with the right arguments:
UserFragment
fragment = new
UserFragment;
Bund
le args =
new
Bundle();
args.putParcelable(ARGUMENT_US
ER, user);
fragment.setArguments
(args)
return
fragment;
}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.
Code lines should not exceed 100 characters. If the line is longer than this limit there are usually two
options to reduce its length:
2.13.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:
+
theFinalOn
e;
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(con
text)
.
load("http://ribot.co.uk/images/sexy
joe.jpg")
.
into(imageVie
w);
Long parameters
case
When a method has many parameters or its parameters are very long, we should break the
line after every comma ,
picture");
loadPicture(context,
"http://ribot.co.uk/images/sexy
joe.jpg",
mImageViewProfilePi
cture,
clickListe
ner,
"Title of the
picture");
Rx chains of operators require line-wrapping. Every operator must go in a new line and the
line should be broken before the .
public Observable<Location>
syncLocations() {
return
mDatabaseHelper.getAllLocation
s()
.concatMap(new
Func1<Location, Observable<? extends
Location>>() {
@Overri
de
public
Observable<? extends
Location> call(Location
location) {
return
mRetrofitService.getLocation(location.
id);
}).retry(new Func2<Integer,
Throwable, Boolean>() {
@Overri
de
})
;
This is
good:
<TextVi
ew
android:id="@+id/text_view
_profile"
android:layout_width="wrap_
content"
android:layout_height="wrap_co
ntent" />
This is
bad :
<!-- Don\'t do
this! -->
<TextVi
ew
android:id="@+id/text_view
_profile"
android:layout_width="wrap_
content"
android:layout_height="wrap_c
ontent" >
</TextVie
w>
3.2 Resources
naming
3.2.1 ID
naming
Element Prefix
TextView
text_
ImageView
image_
Button button_
Menu menu_
Image view
example:
<ImageVi
ew
android:id="@+id/image_
profile"
android:layout_width="wrap_
content"
android:layout_height="wrap_co
ntent" />
Menu
example:
<men
u>
<itemandroid:id="@+id/menu_done"
android:title="Don
e" />
</men
u>
3.2.2
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 belongto any section, then you should follow the rules below:
Prefix Description
error_ An error
message
As a general rule you should try to group similar attributes together. A good way of ordering the
most common attributes is:
Use TODO comments for code that is temporary, a short-term solution, or good-
enough but not perfect.
an
d
// TODO: Change this to use a flag instead of a constant.
Don't hard code any values inside the code. Move them to properties files on constant files. This makes it
easy to manage and change. You don't need to put any comments on the code if the naming is proper.
Write comments only in case you write a complex business logic. Don't make unnecessary API/database
calls. Use caching for less frequent changing data. Follow the KISS principle. It means Keep It Simple
Stupid. (http://en.wikipedia.org/wiki/KISS_principle) Don't write overly complicated code. Don't add
unnecessary permissions in the manifest file. This sometimes cares a user.
Have the key store added to project itself. This avoid different developers using different key stores.
Password should be kept and shared separately. Have proper versioning of different version. In case of
minor fixes just update the minor version. Don't put your name in Packages, Classes or Methods ( During
code review I found some people have created packages with his/her name). Use names which relates to
your application. Create reusable UI components along with their action. Avoid copy pasting the code and
creating replicas. Java Classes
com.exam
ple
activities - Contains all the activities. Classes are all named with
Activity at the end.
fragments – All
fragments
Use slf4j logging framework. Write error/fatal logs in production mode while info logs for development.
Write proper logs in code at different needed places. User at-least 3 level of logging – INFO (general
informational messages), ERROR (business error cases) & FATAL (System failures). Print full exception
stack in mail and in mail. We should have a logger class where we define which logs to come for debug
mode . Only error logs should be enabled for release
binar
y.
Error Handling:
Do proper error handling. The beauty of java is you can catch everything. This helps in controlling error
messages to users and avoiding crashes. The thumb rule is: No screen should show a technical error. All
errors should caught and presented with appropriate error messages. Make the API calls cancellable. This
will avoid crashes in case use has moved to different activity before getting a response.
Unit Testing:
Use JUnit framework for unit testing. Make sure that you cover
70-80% of code using test cases. This will reduce bugs in QA
and reduce the over all effort in project development.
https://developer.android.com/distribute/essentials/quality/core.html
/** * Suppose that the garbage collector determines at a certain point in time that an object is weakly *
reachable. At that time it will atomically clear all weak references to that object. Also, a weak * reference
object is automatically made 'finalizable' and a finalizable object can eventually get * its finalizer
automatically invoked by the JVM. */
private final WeakReference<SampleActivity> mActivity;
With
Threads:
This is Bad:
/*** Example illustrating how threads persist across configuration * changes (which cause the
underlying Activity instance to be * destroyed). The Activity context
also leaks because the thread * is instantiated as an anonymous
class, which holds an implicit * reference to the outer Activity instance,
therefore preventing * it from being garbage collected. */ public class
MainActivity extends Activity {
Gradl
e:
mavenCentral(
)
}Also its good practice to define Min and target sdk version in grade
defaultConfig {
applicationId
“com.example.abc"
minSdkVersion
16
targetSdkVersion 21 versionCode 1
versionName "1.0" }Android Specific Naming Convention
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, Si gnInFragment, ImageUploaderService,
ChangePasswordDialog.2. Resources files
2.1 Drawable
files
Notification notification_
notification_bg.9.png
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
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
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_.
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.
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
3 Resources
naming
3.1 ID
naming
Element Prefix
TextView
text_
ImageView
image_
Button button_
Menu menu_
Image view
example:
<ImageVi
ew
android:id="@+id/image_
profile"
android:layout_width="wrap_
content"
android:layout_height="wrap_co
ntent" />
Menu
example:
<men
u>
<itemandroid:id="@+id/menu_done"
android:title="Don
e" />
</men
u>
Passing objects by Intent: Serializable vs Parcelable
Serializable and Parcelable both are used to pass object by intent in Android application. Parcelable and
Serialization are used for marshalingand unmarshaling Java objects. In Parcelable, developers write custom code
for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization. The
performance of Parcelable over Serialization dramatically improves (around two times faster), because of this
custom implementation.
Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements.
In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection
API. This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects.
Due to this, the Serialization process is slow in comparison to Parcelable.
* use of camelCase for names (and avoid underscore in names) * types start with upper case * methods
and properties start with lower case * use 4 space indentation * public functions should have
documentation such that it appears in Kotlin Doc
## Colon
There is a space before colon where colon separates type and supertype and there's no space where colon
separates instance and type:
``` interface Foo<out T : Any> : Bar {
fun foo(a: Int): T }```
## Lambdas
In lambda expressions, spaces should be used around the curly braces, as well as around the arrow which
separates the parameters from the body. Whenever possible, a lambda should be passed outside of
parentheses.
In lambdas which are short and not nested, it's recommended to use the it convention instead of declaring the
parameter explicitly. In nested lambdas with parameters, parameters should be always declared explicitly.
## Unit
}
```
## Functions vs Properties
In some cases functions with no arguments might be interchangeable with read-only properties. Although the
semantics are similar, there are some stylistic conventions on when to prefer one to another.
### Naming
In Java, it is common to name variables based on their scope. E.g. private `String mSomeString;`. This syntax does
not lend itself well to Kotlin. Instead all variables should be named as lower-camelcase. This makes the variable
more concise and readable.
### Types
When declaring a variable's type, always put a space between the `:` and the type name but not the variable
name.
Do this:
Not this:
Do this:
Not this:
### Naming
Use camelcase for variable naming. This will make for cleaner java interop if necessary. Do not use
Hungarian notation or prefix your variables.
```
val myVal
```
becomes
``` myClass.getMyVal()
```
``` val
my_val ```
becomes ```
myClass.getMy_val() ```
### Declaration
Types can be inferred by the right hand side of a variable assignment in Kotlin. This should be used unless
otherwise necessary.
For example:
rather than:
You should only specify the type of a variable when declaring without an initializer, which is enforced by the
compiler:
// Do something
a = getIntResult() ```
When defining a class always put a space between the closing parenthesis of the primary constructor and
the opening brack of the class body. Parameters in the default constructor should each appear on their
own line:
Do this:
Not this:
```
class User(public open var firstName: String, public open var lastName: String){} ```
If your class is either a subclass or implements an interface the standard formatting rules for type declarations still
apply. There should be a space between the `:` and name of the parent class, but not between the primary
constructor and the `:`:
## Getters / Setters
In Java it is important to provide getters and setters for your member variables. This provides protection from
rework if the implementation changes from being a direct access to the variable to something more complicated.
Say, for instance, your timestamp format changes and you wish to do the conversion under the hood so as not to
have to re-implement much of the processing code. Kotlin, however, uses the concept of "properties". All member
variables automatically have the ability to modify their getters and setters. It is unnecessary to implement getters
and setters for your properties.
mMyString =
str; }```
becomes:
## When Statements
Like switch statements in Java, `when()` bodies should be concise and single line if possible.
Do this:
Not this:
``` return when(myValue) { is
String -> {
var value = myValue + "test" value } is Number ->
String.valueOf(myValue) else -> null }```
If a multi-line body is necessary, break it off into a separate method so that the `when` can remain clean and
concise.
## Nullability
As a rule of thumb, `!!` should never be used and `?` should be used rarely. Theses checks can often be avoided
and doing so will provide for a more stable code-base. Whenever possible, objects and properties should be
made to be not nullable.
## Strings
Do this:
Not this:
A NOTE ABOUT LOGGING: When using Timber, it is recommended to use the varargs as this string substitution
will not be done on Release builds saving time on complex logs.
## Activities / Fragments
Always import the synthetic layouts for your activity or fragment. This cuts down on an immense amount of
boilerplate and keeps your code clean.
Do this:
Not this:
When referencing a parent activity from a fragment, do not call `getActivity()` like you would in Java:
Do this:
Not this:
Do this:
Not this:
## Companion objects
Companion objects should always be defined immediately at the top of the class. Naming conventions for `val`
within a companion object should follow our Java coding standards:
Do this:
Not this:
View click listeners should call `setOnClickListener` directly along with lambda syntax. This avoids the
boilerplate of declaring the right hand side of the assignment and keeps your code clean:
Do this:
``` myButton.setOnClickListener {
myTextView.text = "Hello, ${user.firstName}!" }```
Not this:
Annotations should appear above a class definition, and inline if it is annotating a field in a class:
Do this:
Not this:
## Extensions
Extension functions should only be used if absolutely necessary. Given the option to define a class method vs an
extension function, you should always prefer a class method.