rokas' blog

posts | shitposts

Folding Code Until It's Readable

Code folding is probably nothing new for most developers, whether they use it or not. Modern IDEs and code editors usually display markings for automatically foldable parts of code that you can click to hide a snippet of code such as a method definition.

What might be a slightly less known feature is that a lot of languages offer markings for custom foldable regions. For example, in C# you would use:

#region OPTIONAL_IDENTIFIER
    -- foldable code here --
#endregion

C# was the language where I first learned about this practice (not a jab at it's verbosity, simply first larger project I laid my hands on), and then forgot about it for years.

I remembered it again while working with Flutter. I found that widget definitions were of a length where they were bulky enough to annoy me while navigating code, but not quite big enough to warrant a separate file (in my opinion, as a Dart novice), thus it was a perfect opportunity for me to start using folding again. And as with any new toy, I played with it possibly more than needed.

I had some arrays where I stored multi-choice options for users (e.g. color picker). For readability, I formatted them in a way where each element was a new line. This, of course, lengthened the code significantly, so I was ready to fold it up. However, the IDE did not pick up arrays as automatically foldable, thus I remembered my experience with C# and looked for custom folding markers in Dart to find... that they do not exist.

Of course, this is far from a priority feature for any language, since folding can be implemented on the editor level, and there are already extensions that do exactly that for VS Code. vim, of course, has this feature built-in and expanded upon with multiple types of folding and customising capabilities. Reading about vim always makes switching feel very appealing.

Is custom folding a good idea at all, though? for minimalists, the answer is probably no. If implemented at a language level, it probably adds precious fractions of a millisecond to interpret and parse the code, and of course language developer time, which could be used doing literally anything else.

If you're not a minimalist, though, folding and even custom folding could be pretty useful while writing code. Yes, it is a tool that can be easily used to learn bad practices of cramping code into one file, and it's a bit crappy to use extension-exclusive syntax if you are not the only one working on the project. But if used responsibly, it's a great middle ground between having a bulky file and multiple files that feel just a tad too barren. And if you're stuck with some legacy code that has some 10,000-line monstrosities, this could be a perfect tool for you to prevent carpal tunnel from scrolling.

This post is part of my attempt at #100DaysToOffload.

back