Code Comments
Introduction
The question most people ask is âWhy do we need code comments anyway?â
Code commenting is a very simple way to let someone know what your code is meant to be doing, even if their background in code is weak. Good comments make for easy reading and easy understanding for those who are perhaps not as tech savvy as yourself. Code commenting also explains why you wrote something. At Level 4, the expectation is that you will write basis code comments as a minimum measure to help a reader understand your code.
These are meant for anyone who is likely to consume your source code, but they arenât likely to read through it in any real depth. Code comments are also used by different tools for automatic generation of documentation. If you are building something such as a Library or Framework that you would expect other developers to be using, then you need some form of documentation alongside that, with which comments help the basis of understanding.
It is worth mentioning that several organisations, and open source projects, define specific code style guidelines that must be adhered to. If they donât, however, or you are on your own, keeping this stuff in mind will not only make your job easier in the future, but will also help out anyone who comes after you, too.
Whatâs expected?
At level 4, your code should have comments that help you understand the code youâve written. The comments should also help anyone else who consume your code but likely wonât read through it in any depth. Youâre expected to work through manual code review techniques.
At level 5, your code comments should now help keep your code maintainable by following a consistent standard. You might consider automating your style checks to ensure consistency.
In your final year, youâre expected to build on previous levels by also documenting the APIs you create.
- Follow proper coding standards. Need to be consistent with design. Code should be properly documented and should have generated documentation like API doc (e.g., swagger) or Javadoc.
- A tool should be used, code coverage would be nice.
Header Block Documentation
This style of code commenting is useful in source code for simple explanations of what to expect in that file. For example,
//=============================================================================
// rpg_scenes.js v1.6.2
//=============================================================================
//=============================================================================
/**
* The Superclass of all scenes within the game.
*
* @class Scene_Base
* @constructor
* @extends Stage
*/
function Scene_Base() {
this.initialize.apply(this, arguments);
}
This is a good example of good use of header block commenting. Do not, however, provide a comprehensive list of dates on which the file was altered and new versions have been published. This sort of thing is recorded by your version control system (e.g., git), so you donât need to worry about that aspect when considering version control within your comments.
In-line Documentation
This is the most common type of source code commenting. Do not do line by line code comments, unless you are doing API documentation, as this makes your code unreadable and is just too excessive. You want to tell the reader what your code does, but they donât need a running commentary all the time. You want to guide them through, not pull them through the grass as you are doing so.
Example provided via the Lodash.js documentation.
// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
// Load the FP build for immutable auto-curried iteratee-first data-last methods.
var fp = require('lodash/fp');
// Load method categories.
var array = require('lodash/array');
var object = require('lodash/fp/object');
// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
var at = require('lodash/at');
var curryN = require('lodash/fp/curryN');
Each comment tells someone reading the code what each line is doing. Any questions they have are answered as they are reading through.
Another very common strategy is to document what a function does, such as the following example:
// Checks to see if there's a comment. If so, returns a thank you message.
function sourceCodeComment () {
var comment = document.getElementbyID("Code Comment").value;
if (comment != null && comment != '') {
return console.log("Thank you for your comment.")
}
It might seem like this style of commenting is not necessary when the variable names make it obvious what the code is doing, but you need to maintain the mindset, where not everyone who might read the code necessarily has the same level as you, and so these easy to understand code comments that are situated above the code sections are worthwhile to consider including into your own work.
Clarification Comments
These style of comments are intended for anyone, this can include yourself if you need to leave a project for a while and want to return later. You might also need these comments if your plan is to refactor, maintain or extend upon your existing codebase.
There are times when - after a lot of thought and experimentation - it turns out that the seemingly naive solution to a problem is actually the best. In those scenarios it is almost inevitable that some other coder will come around thinking they are much smarter than you are and start messing with the code, only to discover that your way was the best way all along.
Here is a good example,
/* don't use the global isFinite() because it returns true for null values*/
Number.isFinite(value)
Bad practices not to follow
There will be times when youâll find coding frustrating and might decide to vent your frustrations in the form of comments in your source code that you might accidentally forget to remove (this has happened to me, but thankfully I saw it before my submission).
An example is
/* This code sucks, you know it and I know it. Move on and call me an idiot later. */
It may seem funny at the time, or might help you vent your frustrations, but donât do this.
Another example of code commenting is presented below:
// Start the services
StartServices();
Can you tell why this is bad? It simply states what the code already tells you based on the function/method name that was provided. When writing code comments you need to tell the reader of your code Why this code is doing what it does when it is not possible or easy to infer this by the code itselft.
It is also important to format your comments with readability in mind. This means that you should;
- Tab them appropriately
- Make them brief
- Keep them relevant
- Use them liberally, but not to excess
- Leave spaces where necessary
Coding Standards
When creating your code comments, it is advised that your commenting follows a relevant coding standard. Coding standards are a set of guidelines, best practices, programming styles and conventions that developers adhere to when writing source code for a project. All big software companies have them.
An example of some guidelines, taken from the Linux kernel coding style
a. Tabs are 8 characters, and thus indentations are also 8 characters.
b. The limit on the length of lines is 80 columns and this is a strongly preferred limit.
c. The preferred form for allocating a zeroed array is the following:
p = kcalloc(n, sizeof(...), ...);
Both forms check for overflow on the allocation size n sizeof(âŚ), and return NULL if that occurred.*
A few examples of good coding standards are:
- No more than one statement per line
- Line length should not exceed 80 or 100 characters
- Test class must start with the name of the class they are testing followed by âtestâ.
e.g. ServerConfigurationTest - One character variable names should only be used in loops or for temporary variables
It is important to remember there is a grey area when considering acceptable coding standards and those set out as personal opinion rather than standards that are considered to be good.
Effective Coding Standards
Why exactly do we need coding standards, and what benefits do they offer?
There is a direct relationship between coding standards and software maintainability. There is no doubt that source code that adheres to good standards is simply more readable and reflects harmony, but there is another side to coding standards which is sometimes overlooked at the expense of too much attention to the aesthetics.
Effective coding technqiues focus more on techniques that highlight problems and make bugs stand-out and visible to everyone.
Effective coding standards are:
- short, simple and concise
- they do not attempt to cover and processify everything
- leave plenty of room for developers to exercsie their own creativity
- strike the right balance between formatting issues and issues that âmake the wrong code look wrongâ
- black and white instead of vague suggestions or recommendations
Coding Standards based on Language
Coding Standards differ between programming languages, links to these standards are provided for you below:
- Java
- C Programming which covers:
- C#
- C++
- Web Development which covers:
- Node.js
- PHP
Automate the Process
Once you have developed effective coding standards and are making use of them, you should learn how to automate the process.
Automating the process of checking source codeâs adherence to standards, it will allow you to save a lot of time in peer reviews and allow you to catch everything that humans might miss.
If you are starting fresh and looking for coding standards, start by searching online for well-known standards for your programming language. Start small and remember that there is more than one right way to style the code. There might already be a standard available from the language creators. Your coding standards should check for both style issues and design problems. Once you have standards, make sure that they are adopted by the team and automated. However, code that deviates from standards shouldnât be considered erroneous. It should simply be marked as out of compliance and deviations must be reviewed and fixed.
There is an abundance of style checking tools available for all major programming languages. You
The example image below shows the Checkstyle scan that is used for Java projects.
API Documentation
API documentation is a technical content deliverable, containing instructions about how to effectively use and integrate with an API. Itâs a concise reference manual containing all the information required to work with the API, with details about the functions, classes, return types, arguments and more, supported by tutorials and examples. API Documentation has traditionally been done using regular content creation and maintenance tools and text editors.
Why Document APIs?
Documentation is very important, even for APIs. Documentation is also an area that is showing a lot of growth now, the need for documentation for your API is starting to become even more important than it ever has been before. It is easier to implement code, than it is to write good documentation. This is because of its direct impact, growing adoption and usage. At level 6, you will need to create documentation for any APIs that you create for your projects.
But why do you need to do this anyway? Lets take an example from a popular Machine Learning Library API used within Python: SKLearn. Here is an example of code using guidelines specified on the SKLearn documentation, this gives the user guidelines they should follow when writing code using their Library/API. The API documentation can be found on the scikit-learn website.
from sklearn.utils import check_array, check_random_state
def choose_random_sample(X, random_state=0):
"""Choose a random point from X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
An array representing the data.
random_state : int or RandomState instance, default=0
The seed of the pseudo random number generator that selects a
random sample. Pass an int for reproducible output across multiple
function calls.
See :term:`Glossary <random_state>`.
Returns
-------
x : ndarray of shape (n_features,)
A random point selected from X.
"""
X = check_array(X)
random_state = check_random_state(random_state)
i = random_state.randint(X.shape[0])
return X[i]
The benefits of good documentation, especially in your time after University and in the workplace are:
-
Improved User Adoption - A big reason for having documentation in the first place is that you want users to adopt your software. API documentation improves the experience of developers using your API, which has a direct correlation on API adoption. People adopt products that they enjoy using (and that they find easy to troubleshoot)
-
Increased Awareness - Users beget users. Networking is the most prominent phenomenon of the western market, good networking means stronger possibility to promote your API, leading to increased awareness. Good documentation further improves upon this concept. Donât you always recommend a good product to a friend? Think like that in this instance too, its the same deal
-
Saves Support Time and Costs - Poor or no documentation leads to more frustrated users relying on your team (or yourself) to understand how to work with your API. On the contrary, when you give users the ability to try out the API before implementing it, and arm them with detailed documentation to get started, youâll save your team (and yourself) countless hours responding to support emails and calls
-
Easier Maintenance - Good documentation leads to good product maintenance. It helps your internal teams know the details of your resources, methods, and their associated requests and responses. A popular way that 3rd party developers get help on fixing issues in their API is through using Github to host and allow other developers to fix issues within their software
How to Document your API
There are a number of ways you can document your API. It really depends on which method of API design you have decided on. If you are building your API from scratch, then OpenAPI is a useful tool in helping to automate the process, which will make things easier for you.
When it comes to using API description formats, two important schools of thought have emerged, Design First and Code First. Code First is a more traditional style and approach to developing your API, where you develop the code before the API documentation itself, with Design First being the absolute opposite. For Level 6, exploration of Design First is recommended if it makes sense to use it, but if you are not comfortable with this idea or it is not suitable, then sticking with the more traditional approach is fine too, as long as where necessary you explain your approach direction and justify why you chose this approach. The Design First approach is generally a newer approach and thus doesnât have as extensive a background as the traditional approach of Code First does.
Choose Design First if:
- Developer Experience Matters
- Delivering Mission Critical APIs
- You Need To Ensure Good Communication
Choose Code First if:
- Delivery Speed Matters
- Developing Internal APIs
If you want to choose one of these approaches, how do you decide which approach is going to work best for you though?
- Design First - The plan is converted to a human and machine readable contract, from which the code is built
- Code First - Based on the business plan, API is directly coded, from which a human or machine readable document can be generated
An image showing the approaches compared against each other is included (see figure 1).
Figure 1: Swagger.io Design First vs Code First
References
- Elegant Themes: How to comment your code like a pro
- Submain: 4 reasons we need code comments
- Freecodecamp: Putting comments in code: The good, the bad, and the ugly
- Codeahoy: Effective Coding Standards
- What is API Documentation, and why it matters: Swagger.io Blog
- SKLearn: Developing scikit-learn estimators - Coding Guidelines section
- OpenAPI Specification version 3.0.3.
- Design First or Code First: Whatâs the best approach to API Development?