creature

Global history is unfolding right now. You have a chance to be an active part of it, help Ukraine!

Code Documentation: The Beginner’s Guide

3 Jun, 2022 · 10 min read

avatar
Nazar Omelchenko Software Engineer | Expertise: Angular, Front-end, FinTech Linkedin
Share
Code Documentation: The Beginner’s Guide

Crafting code documentation is one of the things you may try to evade as much as possible. After all, it’s a time-consuming process that requires plenty of regular effort.

‘What’s the fuss? I have tons of work and can’t waste a minute on writing snippets with explanations of this or that code fragment.’ That’s what you might think as a busy programmer. At some point, we are on the same page with you. Our projects also take first place on our agenda. But let’s look at this from a slightly different angle.

Other team members might want to use your code, or a new programmer is welcomed on board, and they might require some guidance. Perhaps, the project has come to a logical end, but there is an urge to get back to it in a year or more.

Once you get the actual value of neatly-documented code, you’ll see things in a different light. If you don’t, just stick with us for some more time.

Today we’ll reveal the true value of well-documented code. We’ll also guide you through the tools that enable a faster code documentation process in the ORIL team. So keep your notepads open – we are starting out.

First Things First – What’s the Code Documentation

Code documentation is the collection of the programmer’s comments that explain how the code works and how it can be used. It comes in various forms and sizes. Documentation can be organized in a shared file with code snippets that include comments about certain blocks and functions. Are you a media type? Then you will immerse yourself in recording video code documentation. Would you like to show that you are not a random guy in the IT world? Then build a full-fledged website with neatly visualized data. A simple file, a detailed handbook, a video guide, or a website – everything works if you keep the core mission of the documentation in mind.

Why Should You Write Code Docs?

A fair question might pop up in your mind, ‘What’s the point of writing ABOUT the code if I can actually WRITE code?’. It makes sense, but hear us out. Your code might not be as straightforward as you think, even for you.

Precious Flashbacks to Momentum

There are times when you grasp the coding groove and code like crazy till you feel that your fingers start to hurt. It’s the time of inspiration, the momentum, and it feels just right. When you get back to it in the morning, you are like, ‘Sorry? And what does this block mean?’. And never say that has never happened to you. When you document your code and explain what every fragment is supposed to do, you spare yourself from the guesswork. You will immediately get the hint of what you meant in every code snippet, and this will save you tons of time. Especially, when you’ve got to dive back in the code several months or even years from now.

That’s Where All Team Members Can Grasp Your Nuggets of Wisdom

If you are a tough programming guru with years of experience under your belt, you may have forgotten how it all started. You looked through the code of a senior dev and thought, ‘He is definitely a smart guy, but I don’t get any of this.’ A documented code could have fixed any misunderstanding and been a great role model for less experienced team members. Besides, when a new software engineer gets enrolled in the team to work on the in-progress project, it might be quite challenging to grasp what is going on. An open-source, well-documented library can save the day. It will add clarity to the team’s decisions and allow the newcomer to get started much quicker.

Documenting Makes Perfect

Code maintenance is the essential part of a good code, yet probably the most challenging one. Without legible and understandable documentation, it would be hard to achieve maintainability. With code documentation, you can streamline all the steps and set the unified names for variables and functions, describe each type, method, return value, give context to further readers, and more.

Code Documentation Tools in the ORIL’s Stack

You’ve heard those horror stories, right? They say that creating code documentation is Sisyphean. But let’s be honest. They are spread by those folks who do not know how to do things right. We no longer live in the Stone age, so creating documentation manually is a sort of an outdated way of doing things. There are code documentation tools that allow you to automate and drastically simplify the process of writing consistent documentation for the whole team. At ORIL, we rely on Storybook and Compodoc to get the tedious code-documenting job done. Haven’t heard of them yet? It looks like the job for us to show you how they work.

Storybook

Storybook is a tool for UI developers that streamlines development, testing, and documentation. In our case, we are interested in the documentation facet of the software, so let’s see how it works and what features it offers.

How Storybook Works

Storybook relies on ‘Stories’ to document UI components, which you will be able to revisit later on-demand. Actually, Story is the Storybook entity that enables you to comment on the code fragments. With this app, you get the tools to expand your basic documentation with layout and prose. For instance, create library usage guidelines or design system sites. Or you can ‘Pin’ or ‘Archive’ the list of tasks that refer to the component.

 

Every Story is a sort of a mini-module for a component and associated metadata. We created a Task.stories.ts file using a template and assigned Default, Pinned, Archived arguments and actions to the components to show you how it works.


export default {
 component: TaskComponent,
 decorators: [
   moduleMetadata({
     declarations: [TaskComponent],
     imports: [CommonModule],
   }),
 ],
 title: 'Task',
 excludeStories: /.*Data$/,
} as Meta;
 
export const actionsData = {
 onPinTask: action('onPinTask'),
 onArchiveTask: action('onArchiveTask'),
};
 
const Template: Story = args => ({
 props: {
   ...args,
   onPinTask: actionsData.onPinTask,
   onArchiveTask: actionsData.onArchiveTask,
 },
});


export const Default = Template.bind({});
Default.args = {
 task: TASK_INBOX,
};
 
export const Pinned = Template.bind({});
Pinned.args = {
 task: TASK_PINNED,
};
 
export const Archived = Template.bind({});
Archived.args = {
 task: TASK_ARCHIVED,
};

As a result, you get a rendered Storybook page, which offers plenty of customization options. The Storybook documentation page is made of building blocks generated automatically based on the components. But again, custom addons give you the freedom to create your own blocks.

Let’s see how the Storybook documentation page will look if we create a more sophisticated file. In his case, we created a component with a list of tasks with various options.

 

That’s the Story for this component:


export const Default = Template.bind({});
Default.args = {
 tasks: [
   { ...TaskStories.Default.args.task, id: '1', title: 'Task 1' },
   { ...TaskStories.Default.args.task, id: '2', title: 'Task 2' },
   { ...TaskStories.Default.args.task, id: '3', title: 'Task 3' },
   { ...TaskStories.Default.args.task, id: '4', title: 'Task 4' },
   { ...TaskStories.Default.args.task, id: '5', title: 'Task 5' },
   { ...TaskStories.Default.args.task, id: '6', title: 'Task 6' },
 ],
};
 
export const WithPinnedTasks = Template.bind({});
WithPinnedTasks.args = {
 tasks: [
   ...Default.args.tasks.slice(0, 5),
   { id: '6', title: 'Task 6 (pinned)', state: 'TASK_PINNED' },
 ],
};
 
export const Loading = Template.bind({});
Loading.args = {
 tasks: [],
 loading: true,
};
 
export const Empty = Template.bind({});
Empty.args = {
 ...Loading.args,
 loading: false,
};

And that’s what you get as the final result. As you see, there is a list of six tasks and the options like Default, With Pinned Tasks, Loading, and Empty.

Storybook Features

Storybook features Canvas and Docs when it comes to code documentation.

Canvas allows you to view the corresponding sidebar item as you click on a story in a preview iframe. Besides, you can navigate between the Stories or use a search to find a Story by name. The bottom menu of the Canvas contains Controls and Actions. Controls depict inputs and outputs, while Actions give you the view of all the activities related to the Story.

 

A Docs section contains a more detailed view of a component, inputs, outputs, and Stories.

 

Also, you can carry unit tests using a separately installed library. For instance, you can check if a pinned task renders on the top of the list.


describe('TaskList component', () => {
 it('renders pinned tasks at the start of the list', async () => {
   const tree = await render(TaskListComponent, {
     declarations: [TaskComponent],
     componentProperties: {
       ...WithPinnedTasks.args,
       onPinTask: {
         emit: () => action('onPinTask'),
       } as any,
       onArchiveTask: {
         emit: () => action('onArchiveTask'),
       } as any,
     },
   });
   const component = tree.fixture.componentInstance;
   expect(component.tasksInOrder[0].id).toBe('6');
 });
});

Storybook Addons

Storybook has plenty of handy addons that extend the use of the tool and customize it. This app comes with essential addons by default (like Docs, Controls, Viewport, Backgrounds, Measure, and more).

But if you would like to obtain advanced customization, there are numerous addons developed by the Storybook team as well as the ones created by third-party developers. For example,

  • Storyshots – allows you to use snapshot testing;
  • Storysource – lets you see the source code since Storybook doesn’t show it;
  • Designs – enables embedding your design preview into the addon panel.

Storybook Advantages

We love this tool at ORIL for a good reason. Storybook has numerous perks that make it a great app for documenting UI code.

  • Instant depiction of UI components.
  • Plenty of helpful addons for more extended use.
  • Superior customization options to meet your task-tailored needs.
  • Unit tests support to check whether individual units flawlessly fit together.
  • Informative documentation and tutorials that help start writing code docs easier and faster.

Storybook Disadvantages

But certain things might make using the Storybook slightly inconvenient.

  • Allows documenting components only (you won’t be able to document code like pipes, services, etc.);
  • Requires creating separate files-stories (sometimes even multiple Stories for big components);
  • Might take some time to grasp all the features and perks of the tool.

Compodoc

Compodoc is a code documentation tool for Angular applications. It comes with a constellation of features to help you generate and maintain the project documentation in seconds.

How Compodoc Works

As you install the app, it generates the project default documentation. It goes through the whole code, detects comments or JSdoc tags, and then cooks up HTML out of it. This feature makes Compodoc more convenient from the outset. For instance, if your project has 3 modules and 30 components, Compodoc will spot and auto-generate them. Thus, you will have the basic documentation right away in mere seconds.

 

Unlike Storybook that uses Stories, Compodoc relies on annotations to document code. As you give your comments on the code, they will be rendered on the page. In this example, we describe the addTask() method.

Compodoc Features

Compodoc will delight you with various handy features. For example, there are plenty of tabs like the Source code (which isn’t available in Storybook by default), Styles, Template, README (if you add .md file), and even DOM tree.

We believe that the strongest feature of Compodoc is Examples that allows you to view the component on any specified page. When you add an annotation tagged with <example-url> and then provide a url to the page with the component, it will be available in the Examples tab. Thus, you can check how the component looks like, how it works, and so on.

Code Coverage is another strong point of Compodoc. It calculates what percentage of the project has been documented. Thus, you will be in the know how the code documenting progress is going.

Compodoc Advantages

Using Compodoc can speed up and simplify the code documenting process in many ways.

  • It’s a simple app, so it won’t eat much of your time to get familiar with all its features.
  • It auto-generates docs from the existing code, so you don’t have to do it manually.
  • It features Code Coverage by default, allowing you to track the documentation progress.
  • You can document code (pipes, services) in this tool.
  • It features various themes for a customized user experience.
  • You don’t have to create separate files for documentation.

Compodoc Disadvantages

However, certain things might not completely meet your code documenting needs.

  • The app’s documentation gives general guidance but not detailed information about how to use the software.
  • Fewer features are available compared to Storybook.
  • You’ve got to redeploy Compodoc after every change. If you work on a big project, this could eat a lot of time.

Wrapping It Up

Well-documented code will benefit a lot of people in the team. For example, junior developers will more eagerly and easily jump into the codebase without a hint of frustration to misunderstand the code. Senior devs will share their pieces of wisdom with less experienced team members without the need to repeat the same thing again and again. Thus, they will invest time in documenting the code once, but several generations of juniors will be thankful for that.

Of course, documenting the code manually can take ages. Thus, there are special tools like Storybook and Compodoc that will help arrange code comments in a user-friendly and consistent way.

Both apps are great, but they serve different purposes and provide various user experiences. Storybook is a worthy choice for UI components, but it lacks some features by default (which you can easily compensate with addons) and will take some time to understand how all the options work. At the same time, Compodoc supports Angular applications and allows instant generation of project docs. It boasts great in-built features, and you will quickly grasp how it works.

Which tool to choose? It’s up to you. But we hope it’s now clear that your projects can no longer exist without code documentation.

5.0/5.0 Article rating
5 Reviews
Was this article helpful? Please rate this article to give us valuable insights for our improvements.
  1. Wow
  2. hidden
  3. hidden
  4. hidden
  5. Pff

Table of Contents

Snapshot Testing: Example and Its Benefits

Snapshot testing has recently become widely popular in front-end development. And for a good reason. As an instrument, snapshot allows running the app through rigorous testing, increasing the test coverage, automating manual processes when writing scripts, and more. So, today we’ll detail the snapshot technology and explain how it works in simple words. First Things […]

avatar
Alexander Panchuk

5 Jun, 2022 · 11 min read

Intro to Agile Methodology: Scrum & Kanban Frameworks

If only creating the digital software were that simple. You just write a piece of code and then make it live. But, alas, things are much more complicated. Because, after all, you strive to build a successful quality app that would meet the needs of end-users within a set timeframe and budget. And this requires […]

avatar
Oksana Zhakpayeva

31 May, 2022 · 16 min read