Apps development for Android step by step

Appendix D: Comments in XML and Java – it’s crucial to create a documentation of Android app

This would be short, but very useful appendix. When you’re programing you know at that specific moment very well what for are some variables, why are you using some methods, how are you going to implement some classes and so on. But two weeks later – believe us – you will spend as much time on trying to understand your existing code as developing new one unless… you add comments.

The professional documentation is crucial in numerous development teams divided into many subgroups working on parts of code. But even if you are alone or in very small team you should do some documentation. At least you should add as many comments to your code as possible.

Good comments could save you hours of trying to figure out... what your code does (Photo Credit

Good comments could save you hours of trying to figure out… what your code does (Photo Credit

Comments could be both in Java code and in XML code, but you add them differently.

Step 1. Short comments in Java (one line comments)

Everything you write after two slashes // is a comment.  This is very useful to explain variable definitions or add some short explanations.

This is also very useful when you want to temporarily “turn off” one line of code. Just add // in front of it.

Step 2. Long comment in Java

If you want to add longer explanation or turn off many code lines, use /* */.

Everything between /* and */ is treated as comment.

It doesn’t matter if there is single line comment inside.

Step 3. Comments in XML

In XML everything you out between <!– and –> is a comment.


Step 4. Typical problems with comments

You can’t use nested comments. Only first comment opening and first comment closing matters. So the example below generates an error as system cannot find opening for */ at the end.

Be careful not to comment just part of instruction. First example “turns off” both condition and increasing variable value and second just condition.

You can’t put comments inside XML tags. You could add them only between tags. The code below generates an error.

You can’t use double minus (–) inside XML comments. Code below would generate an error.

Step 5. Not only comments makes code clear

This sounds obvious, but very important for clarity of code are names of variables, methods and classes. Just “a” means nothing and “age” explains everything, “Bi” class is a secret, “Bicycle” is self-explaining.

Use tabulation and don’t be afraid of free lines and spaces. They won’t make your app bigger or slower.

This is difficult to analyze:

And this is much clearer:

Summary: Commenting takes some time, but for sure you would save much more time due to comments than you waste for writing them. You could easily add comments to Java and XML, though you can’t put comments everywhere.