Best coding practices, tips and more for Android

Bal sikandar
MindOrks
Published in
6 min readJun 10, 2018
Photo by Joshua Earle on Unsplash

I have been a developer for over two years now and the way i have been coding has changed by learning and sharing with others. In these past two years i have seen thousands of lines of code, some were decent, some were ugly and luckily had few sexy ones too. If you’re a programmer and you can read a code like reading a Newspaper, Nothing beats that, Not even the hot girl you follow on Instagram. So let’s dig in.

Coding tips and not tricks

Nested If’s

I hate this, I seriously do, you have statements which require multiple checks like this below code and it goes so deep really deep 💁, In coding which is bad actually 😜.

if (vehicle != null) {
if (vehicle.getCar() != null) {
if (vehicle.getCar().getModel() != null) {
int price = vehicle.getCar().getModel().getPrice();
}

}
}

And the thing is, It can be avoided, you totally can, like this. As you see below one is more readable and easy to understand.

if (vehicle == null || vehicle.getCar() == null || vehicle.getCar().getModel() == null) return;

int price = vehicle.getCar().getModel().getPrice();

Declare defaults

Decide and declare default now in constants if necessary for different primitive or objects that you commonly use. Why? Here it is for e.g. you have a price(String) variable, for which you return null, empty string and “N/A” at different places. Don’t do this. It’s a crime against humanity 😠. Just Pick your favourite because consistency is less error prone.

String Concatenation in loop

The thing is you probably already know some of these things, as you’ll are badass but you’re so badass that you just leave it for your future self assuming he/she will be more badass and will refactor it, ignoring the fact that he/she could be a lazy ass. I hope you get the f***g point 😠.

Nope
for(String name : names) {
name += name;
}
Yup
StringBuilder nameBuilder = new StringBuilder();
for(String name : names) {
nameBuilder.append(name);
}

Naming

Short names for short living variables and good and meaningful for long living ones because they’ll be with you for long-long time. They are family.

For e.g. index variable within for loop can be 'i' but as class variable should be 'index'

Optional

For java this is by far the best solution provided for The billion dollar mistake and it may look like a cheap solution but you gotta use it if you’re hard on cash.

Return

Return empty collections and lists wherever you can don’t return null, otherwise billion will become trillion or do it bro, if you’re a zillionaire 🤑.

Cognitive Complexity

Definition: It’s a psychological characteristic or psychological variable that indicates how complex or simple is the frame and perceptual skill of a person.

In programming a method with nested if else’s and larger size causes high cognitive complexity means less understandability 😕. So better to split large methods into logically separated smaller ones and use above Nested If’s trick to reduce it. Also SonarLint a static code analysis tool calculates this for you in realtime in studio you can use sonar to see how you doing?

Lambda

It’s a must to keep your code precise and curl{} free, as not every curve is good. Luckily with android gradle > 3.0.0 they have built, it’s support in studio check here.

Update

Always update your tools, skills and your language, i mean mind your language kid(Go kotlin/flutter/react/hybrid/native… Our 13 reasons why!!) else this’ll happen.

Google is pissed and they can block your ***.

Region

Use regions to separate your code fragments in big classes like britisher’s did with divide and rule policy, very effective ask indians 🇮🇳.

//region meaningful name of your logically separated regiondo your work here.//endregion

Start

Create start method to launch activity in activity itself to avoid repeating yourself because who loves that and if you’re already using it then bundle the data don’t just pass thousand parameters as below.

public static void start(Context context, Bundle bundle) {
Intent starter = new Intent(context, NextActivity.class);
starter.putExtra(AppConstants.BUNDLE, bundle);
context.startActivity(starter);
}

Max parameters in method

There is no limit for no of parameter allowed in functions but that doesn’t mean you should do it, just like having a GF doesn’t mean you can’t have another but moral people moral. Ideally there shouldn’t be more than 3–4 parameters and if you need more than that use Parameter Object pattern.

Formatting

Code formatting is very important for readability, there should be a vertical and horizontal restriction on code that you put in your methods unless you use your methods for garbage disposal. Studio has a vertical line that shouldn’t be crossed or be prepared to die.

don’t stretch your limit.
wow i like it!

Piece of Advice

John woods. Code for readability

Some good articles For my Android people

Right way to implement Splash screen

From the Big nerds

How to become more productive in android with android studio plugins

How to make the perfect Singleton?

Mindorks

I write here you can follow us, We have people even better than me.

Tools and plugins

You don’t have to know everything, you’re allowed to make mistakes as long someone is overlooking you and telling you bro NO!!!. Try these below tools.

SonarLint

I recommend this, i have been using it and i got to know about this from a colleague, sometimes they can be helpful, kidding. It has several features best one to just scan the modified classes and it’ll automatically criticise you for your bad code and how ugly you can be sometimes. BTW Cognitive complexity we talked earlier it helps.

FindBug

It’s a program that uses static code analysis to find bugs in java code just like SonarLint. To know more about FindBug check this. Fellas flip a coin or whatever but pick one of these tools.

For a list of all the best and most used plugins check below

The coding Principles

SOLID

It’s a mnemonic acronym that helps define the five basic object-oriented design principles:

  • Single Responsibility Principle
  • Open-Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

For complete reference check.

The Boy Scout Rule

Definition: Leave the campground cleaner than you found it

From clean code by uncle bob, I like this rule so when i work on a bad code i refactor, clean, reduce and make it more meaningful and readable than before. Always keep your surrounding’s clean because president is too busy building a wall.

Don’t repeat yourself(DRY)

Never ever write same piece of code twice make it your ironclad rule and people strictly prohibit this in your kingdom.

The Critics principle

Okay it’s totally made up but it’s very logical. When you’re reviewing code of your teammates don’t be a friend, Be their arch enemy, don’t let them make mistakes that you might have to clean someday. Cleaning other’s shit will only make your hand dirty. Enforce good practices in code reviews.

There is more such tips and best practices where it comes from, just click this link, trust me i wouldn’t pop any Ads and you all can contribute, suggest and edit my mistakes. You’ll are good people. I’ll vote for ya.

To be Continued…

Thanks for reading this article. Be sure to click 👏 to recommend this article if you found it helpful. It means a lot to me.

Also let’s connect on facebook, twitter, github and linkedin.

Clap, share if you like it and follow me for the next move.

--

--

Bal sikandar
MindOrks

Android developer @shuttl Ex @_okcredit. Blogger | Open source contributor https://about.me/balsikandar.