Do you keep them in your IDE, or elsewhere? Do you have an app for that? Are they easily shared?
I realized I have no system at all but could use one to make it easier to find code I’ve written and might need again some day.
By snippets, I am referring to any chunk of code / text in any format or language, of any length.
Thanks!
EDIT A DAY LATER: Thanks you all! Reading all these ideas, I got inspired to create my own little web app. Wish me luck… :)
I create proper libraries. I don’t do snippets because they make code dirty, redundant and difficult to read on the long run.
I actively discourage people in my team to use snippets copy and pasted everywhere themselves. If it’s reusable code, it should be usable by everyone and well tested
This. Replace commonly used code snippets well written code that reduces them to one or two lines of code and take advantage of auto-complete in your IDE.
For the rare case where that doesn’t make sense… I’m I’ll ususally find (or create) an extension/plugin for my IDE. Something that can be smarter than any snippet.
The only case I use snippets for is for debug code that I use often. Sometimes there are things I find myself doing a lot for debugging that don’t have any reason to be in code (e.g. nicely formatting certain objects for debug purposes)
Write a function or macro so you can reuse them. The project I work on has dozens of debug assisting code paths. Here are two examples: normally when talking to the db you’ll call
run($sql, $boundVariables)
on a handle. Alternatively you can calldebug($sql, $boundVariables)
to have the handle run the query normally then rerun the query prefixed withEXPLAIN (blah,blah)
to get the execution plan. We also haveassembleEmulatedQuery($sql, $boundVariables)
which will manually replace all the binding tokens in the SQL with their values, do some string escaping and return a big honking string that you can dump into the database… that last one is useful for performance tuning since it can be used to easily capture expensive query forms. Also - assembleEmulatedQuery will throw an exception on our production environment because it’s unsafe due to the potential of SQL Injection.Build debugging functions and add tests over them - future you will thank you!
Please, can you give an example of such code snippets? I’m wondering what people consider reusable in different projects.
Seriously. A snippet library seems like a significant anti-pattern.
Not OP, but I’m thinking about the example in vs code: https://code.visualstudio.com/docs/editor/userdefinedsnippets
Some boilerplate code for libraries and frameworks I constantly use.
I’d be more interested in syncing the VS code snippets as they are automatically available in a file for each language and have the autocomplete stops.If a library or framework requires boilerplate code it’s a bad library or a bad framework.
If a library or framework requires boilerplate code it’s a bad library or a bad framework.
I think this take is uneducated and can only come from a place of inexperience. There’s plenty of usecases that naturally lead to boilerplate code, such as initialization/termination, setting up/tearing down, configuration, etc. This is not a code smell, it’s just the natural reflection of having to integrate third-party code into your projects.
It depends how much boilerplate you need - there’s obviously some stuff that needs to be the same all over but if there’s significant amounts of code you constantly need to replicate that’s when it’s a code smell for me. I probably could’ve been more precise in my initial statement.
Yes, in my experience, boilerplate typically comes into play when you’re using two libraries that don’t know about one another, or have no business touching each other’s concerns. (Using Alpine’s
x-cloak
with Tailwind comes to mind.)That and every single
*-pipelines.yaml
CI/CD config I’ve ever written.
In PHP, a lot. Unit test are boilerplate 90% of the time, getters and setters (although they can be done via Generate), ORM classes with your default shebang (autoincrement ID), and I could go on and on.
I dislike snippets for code like “key this array by some logic” - this should be reusable via a dedicated helper or service.
Getters/setters can also be done automatically by
__get
,__set
or__call
it’s even possible to write a base class or trait that does this automatically.I am a PHP guru, if you’ve ever got questions I’m happy to help.
Sadly that’s against best practices, it does not work with IDE autocomplete, and neither with PHPStan / PHPCS. You also don’t get coverage from PHPUnit. And renaming a property does not rename the usage across the whole project.
__get
and__set
should not be heavily used, and the project shouldn’t be based on them.Some libraries, like Eloquent, uses them well, but you still need to annotate your class with
@property
if you want to stay sane.Please never do any of this
Nah, it’s actually very useful piping and makes code readable and useful.
Let’s say a function, about 20 lines. Something too small to warrant an external dependency but tricky enough that you don’t want to keep rewriting it.
I have things like a function to read through a file of newline delimited text of key-value pairs separated by whitespace. It skips comments (lines beginning with “#”), and returns the pairs. I’m happy to do a little copying instead of having a little dependency.
It is really really easy to make libraries.
I go full chaos and look up where I last used it when I need a snippet…
It’s got to be here somewhere… (Search for way too long…) Dang, I guess I’ll just write it again from scratch
Yeah, this is what I am looking to avoid.
I have a weird knack for reverse engineering, and reverse engineering stuff I’ve written 7-10 years ago is even easier!
I tend to be able to find w/e snippet I’m looking for fast enough that I can’t be assed to do it right yet 😆
Isn’t that what Gists are for? https://gist.github.com/
For github users, yes. I am not one, most of the time.
I keep them in my head, with about 70% accuracy 😹
I would recommend looking into personal knowledge management. I manage mine in Obsidian and treat snippets like permanent notes
Hmmm, I am using Logseq for that kind of note rn, but don’t really like the way it handles code. I assume that’s a markdown problem, not a Logseq one, but I should look again.
Well, Obsidian does have a bazillion plugins that make handling all kinds of content easier. I’m pretty satisfied with the out of the box experience though
I’m using logseq for snippets too. I find it to be adequate. 3 ticks and the language will get you monospace and syntax highlighting:
cd $HOME ls
I selfhost Snippetbox. Real easy, limited in features but does the job!
Thanks. I am thinking about whether a self-hosted service is overkill for this, for my purposes. I kept my question broad in order to find out if most people just keep their snippets on their own PC or what.
I will check this out and I’m also looking at Snibox.
I would appretiate if someone could explain the practical utility of snippets because it just dawned on me how useful they might be.
Easy access to small snippets of code you often need, but putting them in their own library would be crazy.
- Opening a file / db connection
- parsing xml/json/… ,
- template for unit tests,
- import and initialization of framework at work.
Depending on the IDE snippets can also move parts of the code around: (intellij live templates)
- variable.notnull -> if (variable != null) {… }
- “text %s”.format -> String.format(“text %s”,…)
Think about how you write code. Is it all new, or are there functions / API calls / whatever that you might re-use from time to time?
If that’s possible, think about how you go find that code now. Wouldn’t it be cool if you could type a short bit like, “funcA” and boom! your IDE filled in the whole function? Or, worst case, you flip over to another tool, find the snippet you want, copy and paste it into your work.
That’s what I am thinking about, at least. I’m just not sure how I want to get there yet.
You could just write a little terminal utility that puts the string literal of the snippet in your copy buffer with a little search and db for finding the right one and storing new ones— might have to have some weird cases for cross platform tho
I keep my framework-specific reusable code in git repos that I install as git submodules in the repos of actual projects.
For more unique snippets I would ever use rarely I store em in GH gists
I used to let Bob Stout do it for me.
https://web.archive.org/web/19971221055229/https://snippets.org/
SNIPPETS code is tested with PC compilers from Microsoft, Borland, Watcom, and Symantec/Zortech, unless otherwise noted
Borland! There’s a name I haven’t heard in a long time…
My snippets are basically taken care of now by chatgpt.
I mean, I get it. But… damn… can you imagine the relative computing power required to read a text file versus asking a LLM to generate that same text?
Ok.right in the feels.
To be honest, I try to search before on stackoverflow most of the time, due to the ability to write a few keywords and get a suitable answer versus formulate a prompt for the LLM.
But on the other side, llms are used for so much bullshit and invaluable prompts that my questions for helping me in my job has a more worthwile argument.
But of course it is a problematic topic related to llms.
Haha no worries mate I totally get you. One of the best things about LLMs when I’ve played with them is it exercises my ability to write questions and requirements
I’ve only used code snippets in VS Code which can store them in user settings for synchronization. They can also e stored in project settings, which can be optionally synchronized via source control.
I tend not to need them in larger projects where a lot of codegen is available or macros, so I haven’t thought about a solution for things like VS or manual syncing.
I don’t have a library of snippets. Should I?
That’s where I am now. I keep seeing snippets tools and so I asked here. Now that you’ve seen these replies, what do you think?
I assume the answer is very specific to the coding you do & your workflow. There’s no single right answer.
I use https://znote.io, but there are other similar apps, not all free that do the same. Folders + tagging is super useful