Code Snippets - A Beginner's Guide
Tags: beginners, tutorial, productivity, programming
Published: 2019-03-12 15:39:55

---
title: Code Snippets - A Beginner's Guide
published: true
description: A brief how-to on writing your own code snippet.
tags: beginners, tutorial, productivity, programming
cover_image: https://thepracticaldev.s3.amazonaws.com/i/urx6w81tnk4ph9vpebol.jpg
---
![](https://i.redd.it/okjewuj88fl21.jpg)<figcaption>Source: Reddit/r/dundermifflin</figcaption>
One of the first concepts that were driven home by instructors when I started coding bootcamp was the idea that Programmers should "strive to be lazy".   We should use every tool in our arsenal to make writing an application as painless and effortless as possible. If there is a way to not repeat ourselves or to create a shortcut to an outcome that would otherwise involve writing numerous lines of repetitive code, we should take it and not look back. Enter code snippets.  A programmer's best friend.  

<h2>So, What is a Code Snippet?</h2>
"Code Snippet" is a term used to describe a small portion of re-usable source code, machine code, or text. They allow a programmer to avoid typing repetitive code during the course of routine programming. Most modern text editing programs possess some form of Snippet creation and management (I say most because I do not know of every single editor that exists). While the exact way you manage Code Snippets does vary slightly from editor to editor, the basic concept is the same.  For examples I will be using Visual Studio Code.

 

<h3>What Comprises a Code Snippet?</h3>
1. Name - Pretty self explanatory. A name for the snippet.  *This is not what is used to trigger the code snippet in the editor*
2. Prefix - The actual keystroke that will be used to trigger the Code Snippet in the code editor.  Choose a prefix that is easy for you to remember.
3. Body - The actual code that will be copied into the space when you call your code snippet.
4. Description - A simple description of what the code snippet contains.

<h3>Well, why should I even bother using Code Snippets?</h3>
1. They save us from unnecessary amounts of keystrokes (your wrists will thank you). Remember, we should be as lazy as humanly possible whenever we can.
2. They make it easier to remember specific formatting for functions. Some functions can be extremely complex or may contain difficult to remember syntax.  Instead of having to hunt down typos and syntax errors, let a Code Snippet keep your code consistent.
3. They are sharable (Don't be stingy with your Snippets). If you are on a team working on a project, a Code Snippet can help ensure that you are all writing certain blocks of code in the same way - making your code more consistent and more readable.

<h2>Alright...I'm Sold.  How do I Create a Code Snippet</h2>
<h3>Basic Structure</h3>
Lets start with a basic example: We need to write a ton of unique addresses to seed a database for a test environment. (Using Ruby)
Our address scaffolding might look something like:
![](https://thepracticaldev.s3.amazonaws.com/i/i1sxwhy2qap4amz4hxpo.png)
So...every time we want to create a new address we have to type (and fill in the values!):

![](https://thepracticaldev.s3.amazonaws.com/i/v69h8q5wtkqk72rm6m4o.png)
*Puuuuuke* - No thanks.  I can feel my wrists getting sore just thinking about it. Lets create a simple Code Snippet to automate the process. Remember, the instructions may vary slightly based on what code editor you are using but the fundamentals of the steps are pretty much the same:
1. Open up the User Code Snippet interface.  In VS Code: Menu -> Code -> Preferences -> User Snippets. (Or Cmd+Shift+P and search for "User Snippets")
2. Select the language for which you would like to create a Code Snippet (Ruby in this case).
3. Create the basic scaffolding for a Code Snippet:
![](https://thepracticaldev.s3.amazonaws.com/i/m42llbhuewx2wf8ka2zq.png)

4. Awesome.  Now all we have to do is fill in the relevant information for our address:
![](https://thepracticaldev.s3.amazonaws.com/i/hyr8ioppgwu8vx3vuum0.png)
5. Save the User Snippet file and go type `address` (the "prefix" we declared when creating the Code Snippet) in a ruby file to see the fruits of our labor!
![](https://thepracticaldev.s3.amazonaws.com/i/92qx2cr657n4u3xfk1pr.png)
(You can see the description we created!)...now press `Tab` and *BAM!*:
![](https://thepracticaldev.s3.amazonaws.com/i/0er24rmvp73a6sh1vg33.png)
*Note:* You may notice that we removed the quotes that we had in the body of the Code Snippet. Fret not! We are going to improve our Snippet right now by replacing those quotes with "cursor positions" that we can tab through and fill in after creating the snippet.
<h3>Adding Cursor Positioning and Placeholders</h3>
Now that we have a basic structure for the Code Snippet, we can add some cursor positioning so that we can `Tab` through the snippet and add custom text such as variables, strings, or whatever the code requires.  
In VS Code Cursor Positions are created by inserting `${1:"placeholder text"}`, `${2:"placeholder text"}`, `{3:"placeholder text"}`, etc. into the Code Snippet where the number inside of each bracket denotes where the cursor will be after pressing `Tab` that many times. The "placeholder text" is what will display in the Snippet when it is first invoked (use these as a reminder as to what you should type in that place). So using our example:
![](https://thepracticaldev.s3.amazonaws.com/i/l69pw4j1g1xi2wlb66v8.png)*Note: We only need the escapes ("\") because we want our placeholders to be inside of quotations(" ") and without them we are telling the snippet that a line of the body of our snippet ends when the quote closes.*
Now when we call our Code Snippet with `address`:
![](https://thepracticaldev.s3.amazonaws.com/i/uj86zwlika4cy0j1uv6r.png)Yesssss! Now as we enter information and tab through the Code Snippet we can just jump to the next section that we want to fill-in.

<h2> Extras </h2>
1. Multiple lines.  You can create multiple lines in your snippet by simply closing the quotation, placing a `,` at the end, and starting a new set of `" "` on the next line:![](https://thepracticaldev.s3.amazonaws.com/i/bllgnaqjwq7fq4kj2sb3.png)
will produce: ![](https://thepracticaldev.s3.amazonaws.com/i/lp49832txwl10849rnyp.png) *OoooOooOo look, the cursor is also highlighting multiple lines at once..:*
2. Changing multiple cursor points at the same time. You can change more than one cursor point all at once.  In the above example, multiple cursor points are declared with `${1:...}`.  Every one will update at the same time when you begin to input information in the snippet.

So...that's Code Snippets in a nutshell.  They can be as simple or as complex as fit your needs.  I'll leave you with one of my favorite Code Snippets that I have been using. Remember, when you can't remember a piece of code, "Don't Start Trippin', Get Snippin'!"


![](https://thepracticaldev.s3.amazonaws.com/i/imgup56hpumxitey35b2.png)
![](https://thepracticaldev.s3.amazonaws.com/i/1g9e2ggpp5xxyy5fsind.png)

<h3> Resources for different text editors </h3>
<li>[VS Code](https://code.visualstudio.com/docs/editor/userdefinedsnippets)</li>
<li>[Atom](https://flight-manual.atom.io/using-atom/sections/snippets/)</li>
<li>[Sublime Text](http://sublimetext.info/docs/en/extensibility/snippets.html)</li>

![](https://i.redd.it/bo6r40h6uvk21.png)<figcaption>Source: Reddit/r/dundermifflin</figcaption>