MOBILOITTTE - ANDROID+KOTLIN-Coding Guidelines

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Coding Guidelines | Android

1 Java language
rules

1.1 Don't ignore


exceptions

You must never do the


following:

void setServerPort(String
value) {

try {serverPort = Integer.parseInt(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.

1.2 Don't catch generic


exception

You should not do


this:

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!

}See the reason why and some alternatives here

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

1.4 Fully qualify


imports

This is bad: import


foo.*;
This is good: import
foo.Bar;

See more info


here

2 Java style
rules

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.

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
;

}2.2 Treat acronyms as words

Good Bad

XmlHttpRequest
XMLHTTPRequest

getCustomerId
getCustomerID

String url String URL

long id long ID

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

2.4 Use standard brace


style

Braces go on the same line as the code


before them.

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.

More information about annotation guidelines can


be found here.

2.5.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 .
/* 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;

2.6 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.7 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:

1. Android imports 2. Imports from


third parties (com, junit, net, org) 3.
java and javax 4. 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).

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:

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
MyClas
s{

private static final


String TAG =
MyClass.class.getSimpleNa
me();

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

2.9 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

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 {

//Order matches Activity


lifecycle

@Overri
de

pu
blic void
onCreate(
) {}

@Overri
de

pub
lic void
onResume
() {}

@Overri
de

pu
blic void
onPause(
) {}

@Overri
de

pu
blic void
onDestroy(
) {}

}2.10 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.

Exampl
es:

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

// Callbacks always
go last

public void loadUserAsync(Context context, int userId,


UserCallback callback);
2.11 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.

Exampl
e:

// 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";

2.12 Arguments in Fragments and


Activities

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.

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_US
ER, 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;

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.

2.13 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.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:

int longName = anotherVeryLongVariable + anEvenLongerOne -


thisRidiculousLongOne

+
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 ,

loadPicture(context, "http://ribot.co.uk/images/sexyjoe.jpg", mImageViewProfilePicture,


clickListener, "Title of the

picture");
loadPicture(context,

"http://ribot.co.uk/images/sexy
joe.jpg",

mImageViewProfilePi
cture,

clickListe
ner,

"Title of the
picture");

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

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

public Boolean call(Integer numRetries,


Throwable throwable) {

return throwable instanceof


RetrofitError;

})
;

}3 XML style rules

3.1 Use self closing


tags

When an XML element doesn't have any contents, youmust use


self closing tags.

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

Resource IDs and names are written in


lowercase_underscore.

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

<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

msg_ A regular information


message

title_ A title, i.e. a dialog


title

action_ An action such as "Save" or


"Create"

3.2.3 Styles and


Themes

Unless the rest of resources, style names are written in


UpperCamelCase.
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:

1. View Id 2. Style 3. Layout width and


layout height 4. Other layout attributes,
sorted alphabetically 5. Remaining
attributes, sorted alphabetically 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.

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

Some General Guidelines:

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.

adapters – contains all the


adapters

authenticator – all classes related to different


authenticators

data – data management (Content Providers,


Sqllite helpers)

fragments – All
fragments

helpers - Contains helper classes. A helper class is a place to put


code that is used in

more than one place. Most of the methods are static.


Example DateHelper

Interfaces – Contains all the


interfaces

models - Contains all local


models.

You can have sub-package according to logical entities like


different departments.
Logging:

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.

Android Best Practices

https://developer.android.com/distribute/essentials/quality/core.html

Avoid Memory Leaks:


In Java, non-static anonymous classes hold an implicit reference to their enclosing class. If you're not careful,
storing this reference can result in the Activity being retained when it would otherwise be eligible for garbage
collection. Activity objects hold a reference to their entire view hierarchy and all its resources, so if you leak one, you
leak a lot of memory. With Handler: //This is Bad and leaks Memory public class SampleActivity extends Activity {

private final Handler mLeakyHandler = new Handler() {


@Override public void
handleMessage(Message msg) {
// ... }
} }//This is Good

public class SampleActivity extends Activity {

/*** Instances of static inner classes do not hold an implicit


* reference to their outer class. */ private static
class MyHandler extends Handler {

/** * 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;

public MyHandler(SampleActivity activity) {


mActivity = new WeakReference<SampleActivity>(activity);
}@Override public void handleMessage(Message msg) {
SampleActivity activity = mActivity.get(); if
(activity != null) {
// ... } }
}

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 {

@Override protected void onCreate(Bundle


savedInstanceState)
{ super.onCreate(savedInstanceState);
exampleOne(); }private void exampleOne() {
new Thread() {
@Override public
void run() {
while (true) {
SystemClock.sleep(1000); } }
}.start(); } }
This is Good:/**
* This example avoids leaking an Activity context by declaring the * thread as
a private static inner class, but the threads still * continue to run even across
configuration changes. The DVM has a * reference to all running threads and
whether or not these threads * are garbage collected has nothing to do with
the Activity lifecycle. * Active threads will continue to run until the kernel
destroys your * application's process. */ public class MainActivity extends
Activity {

@Override protected void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);
exampleTwo(); }private void exampleTwo() { new
MyThread().start(); }private static class MyThread extends Thread {
@Override public
void run() {
while (true) {
SystemClock.sleep(1000);
} } } }Build:

Gradl
e:

in Build.gradle pls make sure that repositories is included with


mavenCenteral(). exp: repositories {

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

Resources file names are written in


lowercase_underscore.

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

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

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

Resource IDs and names are written in


lowercase_underscore.

3.1 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:
<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.

So Use Parcelable to send objects by intents, also by other


means like Handlers.

Coding Guidelines | Kotlin

If in doubt default to the Java Coding Conventions such as:

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

``` list.filter { it > 10 }.map { element -> element * 2 } ```

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

If a function returns Unit, the return type should be omitted:

``` fun foo() { // ": Unit" is omitted here

}
```

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

Prefer a property over a function when the underlying algorithm:

* does not throw * has a O(1) complexity * is cheap to calculate (or


caсhed on the first run) * returns the same result over invocations

## Vokal Specific Standards

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

``` val name: String


```

Not this:

``` val name : String ```


If at all possible, ignore explicit usage of the `Unit` type. Most commonly this would be in the case of a
function that returns `Unit`:

Do this:

``` fun doSomething()


```

Not this:

``` fun doSomething(): Unit ```

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

``` val a = 100 // Int is inferred ```

rather than:

``` val a: Int = 100 // Int is redundant ```

You should only specify the type of a variable when declaring without an initializer, which is enforced by the
compiler:

``` val a: Int

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

``` class User(


public open var firstName: String, public open var
lastName: String ) {} ```

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

``` class User(


public open var firstName: String, public open var
lastName: String ): RealmObject() {} ```

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

``` private String mMyString;

public String getMyString() {


// Some special getter implementation }public
void setMyString(String str) {

mMyString =
str; }```

becomes:

``` public var myString: String = ""


get() = // some special getter implementation // Implicit standard
setter ```

## When Statements

Like switch statements in Java, `when()` bodies should be concise and single line if possible.

Do this:

``` return when(myValue) {


is String -> myValue + "test" is Number ->
String.valueOf(myValue) else -> null }```

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

Always prefer string interpolation if possible:

Do this:

``` val fullName = "${user.firstName} ${user.lastName}" ```

Not this:

``` val fullName = user.firstName + " " + user.lastName ```

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.

Always prefer Kotlin-esque direct property accesses whenever available:

Do this:

``` myTextView.text = "Hello, ${user.firstName}!"


myTextView.visibility = View.VISIBLE ```

Not this:

``` myTextView.setText("Hello, ${user.firstName}!")


myTextView.setVisibility(View.VISIBLE) ```

When referencing a parent activity from a fragment, do not call `getActivity()` like you would in Java:
Do this:

``` val typefaceSpan = CalligraphyTypefaceSpan(


TypefaceUtils.load(activity.assets, "fonts/BooterFiveZero.ttf")) ```

Not this:

``` val typefaceSpan = CalligraphyTypefaceSpan(


TypefaceUtils.load(getActivity().getAssets(), "fonts/BooterFiveZero.ttf")) When defining a class-
level constant, normal naming conventions apply: ```

Do this:

``` class MyFragment: Fragment() {


private val TypeViewHeader = 0 private val
TypeViewFooter = 1 }```

Not this:

``` class MyFragment: Fragment() {


private val TYPE_VIEW_HEADER = 0 private
val TYPE_VIEW_FOOTER = 1 }```

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

``` class MyFragment: Fragment() {


companion object {
const val TYPE_VIEW_HEADER = 0 const val
TYPE_VIEW_FOOTER = 1 } }```

Not this:

``` class MyFragment: Fragment() {


companion object {
val TypeViewHeader = 0 val
TypeViewFooter = 1 } }```
## Views

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:

``` myButton.setOnClickListener = (object : View.OnClickListener() {


myTextView.text = "Hello, ${user.firstName}!" })```
## Annotations

Annotations should appear above a class definition, and inline if it is annotating a field in a class:

Do this:

``` @Root(strict=false) public


open class User (
@field:Element public open var firstName: String? = "", @field:Element public
open var lastName: String? = "", ) {} ```

Not this:

``` @Root(strict=false) public open class User (


@field:Element public open var firstName: String? = "",
@field:Element public open var lastName: String? = "", ) {}
```

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

You might also like