Best Practices
Here is a list of best practices related to Android and development in general used to keep the code readable, maintainable and consistent. General concepts are taken from the Clean Code book by Robert C Martin.
- Avoid duplication in your code (DRY principle - Don’t repeat yourself). Whenever you see that you need to write the code twice then it is an indication that it needs to be in a separate function / reusable view etc.
- Functions should be short and do only one thing. If your function is doing more than “one thing,” it is a perfect moment to extract to another function.
- No more than 10 lines is a good standard.
- Give good meaningful names for classes, functions, variables etc. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.
- It is best to write them in English and not for example in Estonian. Even comments.
- Classes and object names should be nouns or noun phrases. Like “Plant” and “PlantDetails”.
- Function names should be verbs or verb phrases, not nouns. Like “onClick”, “getPlantDetails” and “setButtonStyle”.
- Good code does not need comments to understand it. If you are tempted to write a comment in your code then ask yourself
- Is it really necessary?
- Can I change the variable/function/class name to make it more understandable?
- Can I move code into smaller functions so it is more clear?
This doesn’t mean there should be no comments in the code, it means to be conscious when writing a comment and doing it only when it is really needed.
- If you starting a project with a team - lay down the style rules and write them down somewhere. If you are contributing to an existing project - keep using the same style that is used in the project. The most important is to keep it consistent.
Android Specific Best Practices
Themes and Styles. Use camelCase for names.
Dimens and Colors. Use snake_case for names.
Strings.xml. Use snake_case for names. Group your strings by the view where they are used and give them a prefix. This way it is clear also for the other devs (and you) where these strings are used.
<string name="login_email">Email</string> <string name="login_password">Password</string> <string name="login_button">Login</string> <string name="dashboard_welcome">Welcome, %s!</string> <string name="dashboard_settings">Settings</string>
XML files. Short story: Use camelCase.
Long story: Historically it used to be snake_case (just like dimens, colors and strings). But now with ViewBinding where in Activity and Fragment it converts your snake_case view ids into camelCase names then it makes sense to just use camelCase right away in the XML file.
Logging with LogCat. A common practice is to use the class name for the Log Tag. To avoid hardcoding a string for the value, you can set it like so:
companion object { val TAG = MyClass::class.java.name }