Why we use code alignment in Android Studio
Technology
2
 min read
August 17, 2021

Why we use code alignment in Android Studio

Peter Bergmann
Peter Bergmann
Android Developer

For our GoodRequest Android team, the most important aspect of programming is the readability. We want our code to be readable because it affects all the main goals of our company. You can’t create apps that are error prone, easy to maintain, easy to modify, etc. if your code is messy and hard to understand.

When we develop Android apps, we prefer readability over ease of writing. There are a lot of things that affect code readability like names of variables and functions, language syntax, use of pure functions, etc. But readability can be also increased by good code alignment. And this doesn’t only mean how many tabs or spaces you use. Aligning the same parts of code in columns can help you see what is different. Or it can help you ignore what is the same.

For example when you are creating data classes with more fields. It is more readable when you put field names in one column and data types in another.

Or if you declare a function with more parameters. It is easier to read parameter names and their data types.


Another example is something repetitive as setting string values to TextViews.

If you align the same code in columns you can easily see the mistake now (shift TextView is set with wrong string :) ), because you can visually ignore the same parts and focus on what is important.

We use code alignment like this a lot and it can be quite time consuming. So we decided to create a plugin for Android Studio called GoodFormatter.

It’s limited to 50 lines of code because it’s quite heavy to process long strings and align them. We are working on version 2.0 which will use PSI tree data structure and therefore allow us to optimize the alignment process.

But there are drawbacks too. So to sum things up let’s look at pros and cons.

Pros:

  • easier to read
  • code looks cleaner
  • can help to see some errors

Cons:

  • commits may contain more whitespace changes (this can be eased for example by github hide whitespaces changes)
  • it doesn't always make sense so you must think more when to use it
  • adding line may require editing all the lines so it can be time consuming (but when you use our plugin it doesn’t have to be :) )

Like what you see?
Join our newsletter.

Great! Welcome to newsletter.
Oops! Something went wrong while submitting your email.
High quality content once a month. No spam, we promise.
Your personal data is processed in accordance with our Memorandum on Personal Data Protection.

Páči sa vám náš content?
Odoberajte newsletter.

Great! Welcome to newsletter.
Oops! Something went wrong while submitting your email.
Vaše osobné údaje sú spracované v súlade s našim Memorandom na ochranu osobných údajov.