Android Good Practices
Simple concept to know while building an android project
Introduction
Due to tight deadlines, we tend to produce codes that are better for the primary time, resulting in a large number of codes and repetitions, making the project difficult to read.
I recently worked on a project where I made a simple but costly error, which resulted in additional time spent modifying and cleaning the codebase.
I'll be writing about a simple principle that should be adopted in order to avoid making such blunders as a beginner when working on any project. Small errors like this might lead to countless hours of reworking.
Simple things to look out for
- Formatting of code
- Storing hard-coded string in the value/string.xml file
- Storing dimension in values/dimen.xml file
- Storing colour in value/colour.xml file
The res/value folder holds all resources used in the android project like strings,colour, dimension and styles.
1. Formatting code
Not formatting your code makes it difficult to understand, makes it harder to notice potential bugs in your project, and makes it difficult for someone else to read your code later on. Formatting, in a nutshell, increases readability.
To format your code, navigate to the file you want to format and highlight the whole code in the file. On the top menu bar click on the Code option, inside click on the Reformat Option to format your code in the specific file
2. Storing hard-coded strings
The versatility of translating your program into different languages is limited by hard-coded strings that are static. You'll have to go through the project and replace every single string.
Hard coding strings into your layout files is not a smart idea. You should save them in a string resource file and then use them in your layout. This allows you to update every instance of a word, such as "Voting results", in all layouts at the same time by just updating your strings.
Before storing the hardcoded string
After storing the hardcoded string
3. Storing of Dimension
A dimension is defined by a number and a unit of measurement, such as 5dp, 3sp, and so on. Dimensions can be stored in a res/dimen.xml file and reused throughout your project.
Before storing the dimension
After storing the dimension
Storing of colour
Colours too are not left out which are also stored in a res/colour.xml file for reusability.
Before storing the colours
After storing the colour
Conclusion
These small ideas may seem insignificant, but they can go a long way toward making your project more readable and with less repetition.
I hope you find this information to be very useful.