Code Snippets For You, Part 1

Every coder has to deal with some repetitive tasks when they create a new application. Every new file added to your growing application, has some common properties, apart from selected language. Moreover, if you're into design patterns, these common properties become harder to repeat everytime you need them. Of course, i know, there are modern editors with code snippet support in these days.

However I invite you to imagine some apocalyptic scenario in which some crazy virus destroyed all Code-Snippet-Supporting-Editors. So we need to create our own code snippets, in order to re-create Code-Snippet-Supporting-Editors.

Someone has to do it, right?

Our homebrew snippet system consists of two parts: templates and scripts.

  • Templates are the customizable content for our snippets,
  • Scripts are simple programs to generate project specific code from provided templates.

And as a design criterion, scripts will work at the file level and used to add the new file(s) to user projects.

Here is the usage scenario :

$ add_class Warrior
$ add_class Warlock

After these commands invoked, we expect following 4 files to be created in working directory:

For Warrior,

And for Warlock,

To create files above, we need to write two template files; one for headers, and another for source files.

Class Header Template

If we consider similarities between header files given above, we can write our header template like this:

As you may notice, we use [[Name]] as a template variable for replacing the real class name. We select double brackets for delimiting variable name, but it's ok to use something else, as long as we didn't pick some pattern which would occur accidentally in our template code.

Also, there are two different cases for our template variable in the template file, an uppercase representation ([[NAME]]) for include guards, and a CamelCase representation ([[Name]]) for other uses.

Class Body Template

Just like header template, we can write down following source template by comparing cpp files:

End of Part 1

In the next post, we code add_class script in python language. Just like in our usage scenario, it will take provided parameter as the name of a class, and use our templates, produce source and header files in our working directory.