DEV Community

Cover image for Code Snippets - A Beginner's Guide
Matthew Brophy
Matthew Brophy

Posted on

Code Snippets - A Beginner's Guide

Source: Reddit/r/dundermifflin

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.

So, What is a Code Snippet?

"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.

What Comprises a Code Snippet?

  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.

Well, why should I even bother using Code Snippets?

  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.

Alright...I'm Sold. How do I Create a Code Snippet

Basic Structure

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:

So...every time we want to create a new address we have to type (and fill in the values!):


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:

  4. Awesome. Now all we have to do is fill in the relevant information for our address:

  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!

    (You can see the description we created!)...now press Tab and BAM!:

    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.

    Adding Cursor Positioning and Placeholders

    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:
    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:
    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.

Extras

  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: will produce: 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'!"


Resources for different text editors

  • VS Code

  • Atom

  • Sublime Text
  • Source: Reddit/r/dundermifflin

    Top comments (9)

    Collapse
     
    fioribazarello profile image
    Fiori Bazarello

    In VS Code is also possible to configure options in positions:

    ${1|optionOne,optionTwo|}
    
    Enter fullscreen mode Exit fullscreen mode

    For example, to create a new React component:

    class ${1:classname} extends React.${2|Component,PureComponent|} {}
    
    Enter fullscreen mode Exit fullscreen mode
    Collapse
     
    matthewbrophy profile image
    Matthew Brophy

    Thank you for pointing that out. That is very useful!

    Collapse
     
    eroberts profile image
    Ethan Roberts

    I found this website so helpful for this: snippet-generator.app

    Collapse
     
    matthewbrophy profile image
    Matthew Brophy

    Thanks! I love this tool. Awesome resource.

    Collapse
     
    iamvictor profile image
    Victor Ikechukwu

    This was such a good read, and quite funny 😄. Thank you Mathew :)

    Collapse
     
    newdevrising profile image
    Tom

    This is very helpful. Thank you.

    Collapse
     
    matthewbrophy profile image
    Matthew Brophy

    Glad I could help! Thanks Tom!

    Collapse
     
    mimic profile image
    Dokupendium

    Just an awesome Intro, great writing style! I think you just got one more follower 🐬

    Collapse
     
    otisgbangba profile image
    otisgbangba

    Thanks Matthew for your contribution. Please could you be of a coaching assistance on how to code a snippet that can replace all the vowels in a document with Cyrillic letters.