10 Best Practices of Java in Android

Amit Kumar
4 min readDec 2, 2016

--

In this story, I am sharing what i have learnt in the journey of Android Development. I always think to write code in terms of APIs (Application Programming Interfaces). Of course, there may be ten different ways to write a program but seven of them will be inefficient and not reusable. Well, this is not a complete set of practices but these must be in a developers’ toolkit. Here are some of the practices -

1. Use static factory methods instead of constructors

You don’t need to create a new object each time, they’re invoked.

Static method example

2. Use builders when there are many constructor parameters

When there are some required and some optional parameters, Builder pattern is better than telescoping pattern. In short, whenever there is more than 3 parameters, you must consider builder rather than constructors.

public class BlogPost {

private final String post_title;
private final String post_description;
private final String author;
private final long posted_on;
private final int num_of_likes;
private final int num_of_comments;

public static class Builder {
//Required Parameters
private final String post_title;
private final String post_description;

//Optional parameters
private String author = "";
private long posted_on = 0l;
private int num_of_likes = 0;
private int num_of_comments = 0;

public Builder(String post_title, String post_description) {
this.post_title = post_title;
this.post_description = post_description;
}

public Builder author(String authorName) {
author = authorName;
return this;
}

public Builder posted_on(Long posted_on) {
posted_on = posted_on;
return this;
}

public Builder numLikes(int val) {
num_of_likes = val;
return this;
}

public Builder numComments(int val) {
num_of_comments = val;
return this;
}

public BlogPost build(){
return new BlogPost(this);
}
}

private BlogPost(Builder builder){
post_title = builder.post_title;
post_description = builder.post_description;
author = builder.author;
posted_on = builder.posted_on;
num_of_likes = builder.num_of_likes;
num_of_comments = builder.num_of_comments;
}
}

Then you can use it as follows

BlogPost blogPost = new BlogPost.Builder("My First Post", "description of my post").author("Amit Kumar").numLikes(2).build();

3.Best way to implement a singleton is to use single-element enum.

public enum BlogPost {
INSTANCE;

public void buildPost() {...}
}

4. Always override toString

It is recommended that all subclasses must override this method. Providing a good toString implementation, helps you in generating a useful diagnostic message. But you must clearly document your intentions and specify the format.

5. Immutable class are easier to design and use than mutable class.

To make a class immutable, you must follow these 5 rules.

Don’t provide any methods that modify the object’s state

Ensure that the class can’t be extended.

Make all fields final.

Make all fields private.

Ensure exclusive access to any mutable components.

6. Use static member classes over non static

If you have a nested class that doesn’t depend or serve any other class except the enclosing class it must be a top-level class. Otherwise if that class doesn’t not access an instance of enclosing class, it must be a static class. It helps you to prevent memory leaks.

7. Use enums instead of int constants

public enum Apple { FUJI, PIPPIN, GRANNY_SMITH }
public enum Orange { NAVEL, TEMPLE, BLOOD }

Enums provide compile-time type safety. If you declare a parameter to be of
type Apple , you are guaranteed that any non-null object reference passed to the parameter is one of the three valid Apple values. Attempts to pass values of the wrong type will result in compile-time errors so they can be easily removed at compile time.

8. Return an empty array or list, not nulls

public List<Post> getPosts() {
if (posts.size() == 0)
return null;
...
}

There is no need to return null when no posts are available. You can simply return an empty array. Doing this, will help client to write less code that is client won’t need to check null.

public List<Post> getPosts() {
if (posts.size() == 0)
return Collections.emptyList();
...
}

9. For-each loops are faster than traditional for loops

private List<User> userList;
//Traditional for loop
for (int i = 0; i < userList.size(); i++) {
doSomething(userList.get(i));
}

//for-each loop
for (User user : userList) {
doSomething(user);
}

For-each loops are more efficient to iterate over a list and array.

10. Use lazy initialisation judiciously

Lazy initialisation is an approach of delaying the initialisation of a field until it is needed. In most of the cases, normal initialisation is preferable to the lazy one because lazy initialisation doesn’t improve the performance significantly and as it is slow so the normal one is preferred. The best advice is “don’t do it unless you need to”.

--

--

Amit Kumar

Founder | Building eCommerce 3.0 | Software Engineer