Code snippets

Introduction

If you are a developer and already have some experience working on projects, then you are familiar with the concept of code repetition. Indeed, who hasn't said to themselves, "This is the fifth time I've rewritten this piece of code, in several different files with three variables that change." You might say that good old copy and paste does the trick, and you'd be right. But what if I told you that you could do it generically, with variables?

Enter the snippet, or code snippet! Although it's a small feature, it saves a huge amount of time. A piece of reusable code that will increase your efficiency and productivity.

In this article, we will define in more detail what these famous snippets are before exploring their implementation and use. After that, we will discuss the advantages they can bring to a developer, while also considering a project as a whole.

1. What is a code snippet?

A code snippet (simplified as snippet) is a customizable and reusable block of code. It is structured in different parts:

				
					"Generate private method" : {
        "prefix" : "p-method",
        "body" : "private method() : void { return; }",
        "description" : "Create a basic private method"
    }

				
			

In this example:

  • "Generate private method" is the name of the snippet.
  • "prefix" defines the shortcut to type to trigger the snippet.
  • "body" contains the code that will be generated by the snippet. It can include generic markers ($1, $2, etc.).
  • "description" is a short explanation of what the snippet does.

There are two main categories of snippets: IDE snippets and library or framework snippets.

  • IDE snippets are linked to the language you use for coding (HTML, JavaScript, C#, etc.).
  • Library or framework snippets are linked to the context of your project. For example, with Angular, you can have a snippet dedicated to generating the body of a form.

2. Installation and use

In this article, I am using Visual Studio Code as my IDE, but most tools such as Visual Studio, Sublime Text, and others support the use of snippets.

You don't need to be a senior developer to understand the main advantages of snippets: speed and efficiency.

To return to my example in the introduction:

				
					"Generate private method" : {
        "prefix" : "p-method",
        "body" : "private method() : void { return; }",
        "description" : "Create a basic private method"
    }

				
			

Once this snippet is set up, simply typing "p-method" will cause the snippet to be suggested by the IDE's IntelliSense.

By pressing "enter," the snippet will run and generate the code:

Going further with generic markers

If you find this example a little too simple, let's make it a little more complex with generic markers. Generic markers (or tabstops) are numbered markers (here $1, $2) in the body of the snippet that mark the navigation order of the cursor through the generated code snippet:

				
					"Generate private method" : { 
        "prefix" : "p-method", 
        "body" : [ "private method($1) : void { ",
                    "$2",
                    "}" 
                ],
        "description" : "Create a basic private method" 
    }


				
			

In this example, the generated code will be the same. However, the cursor will automatically be placed where the $1 marker is located. Once the parameter has been defined, if you press the Tab key, your marker will automatically move to the next marker, $2, allowing you to write the content of the method.

Note that here, "body" now represents an array of strings, each element corresponding to a line to be generated.

And what happens if you repeat the same marker several times? This is a question that the most observant among you may already be asking yourselves. Quite simply, whatever you write will be repeated!

Let's take the following excerpt:

				
					"Generate private method" : { 
        "prefix" : "p-method", 
        "body" : [ "private method($1: $2) : $2 { ",
                    "return $3",
                    "}" 
                ],
        "description" : "Create a basic private method" 
    }



				
			

Here, you can see that I have the $2 marker twice. From now on, when I write the type of the expected parameter in the method, I will define this same type as the expected return of my method.

Placeholder and list of options

Still too simple? Keep in mind that generic markers can also contain placeholders with specific text that you want to be displayed by default, or even a list of options!

  • Snippet with placeholder:
				
					"Print to console" : {
        "prefix" : "log",
        "body" : [
            "console.log('${1:Hello world}');",
            “$2”
        ],
        "description" : "Log output to console"
    }




				
			

Here, by default, the text "Hello world" will be written in "console.log()".

  • HTML snippet with option list
				
					"Create button" : {
        "prefix" : "button link",
        "body":  "<button class='${1|primary,secondary,success,warning,danger|}'>$2</button>",
        "description" : "Create a link button"
    }





				
			

When creating your button, you will be able to choose from the different values provided! Of course, you can always enter another character string.

3. Advantage at every level

For a developer who has to write an average of 500 to 700 lines of code per day, snippets greatly reduce the feeling of repetitiveness, wasted time, and typing errors. You can now focus more calmly on thinking and logic, which improves the quality of the code.

Meanwhile, the benefits are not limited to writing code faster. In a project context, they enable code standardization :

  • Consistency: Ensure that methods, classes, etc. are written in the same format.
  • Best practices: For example, to take another example, the inclusion of "aria-hidden" by default for icons or other accessibility practices for frontends.

These points make it particularly easy for newcomers to get started on a project, maintain consistency despite turnover, and simplify your work on personal projects.

Conclusion

In short, snippets go beyond the simple role of keyboard shortcuts.
They are valuable tools that assist you on a daily basis, saving you time and improving quality. Whether you are a novice developer or have years of experience, they allow you to focus on what matters most: logic and thinking.

Finally, don’t wait for your next big project or the development of a new product to get started! Start by creating snippets for the three blocks of code you write most often. Experiment and find the approach that works best for you! Once you get used to it, you’ll find it hard to do without!

Image by Yann LECORRE

Yann LECORRE

Fullstack Developer

Share this article

Share this article

Contents

Read also

Read the article
Read the article
Read the article