Home » Software Development Resources » Custom Code Folds: Know When to Fold’em

Custom Code Folds: Know When to Fold’em

Organization is the hallmark of any good developer and nothing makes organization more difficult than a long file. I’ve often run into long files in scripting languages like python, where a module could be thousands of lines long. I find it incredibly frustrating to scroll thousands of lines to look at a method reference only to lose my place when I need to scroll back to where I started. That’s why I find custom code folding so useful.

Custom Code Folds: Know When to Fold’em

What is Code Folding?

Cold folding is when an IDE can collapse a portion of code on the screen. Often times the IDEs do this automatically based around Class or Method scope. Usually it is shown as a plus or minus sign in the left margin of the code editor. For more details check out the resources below.

collapse

What if you want to fold more than one code block into a group, or the IDE messes up the fold scope?

Custom Code Folding

Most IDEs allow the developer to specify tags in line comments to instruct the browser what regions to collapse. I’ve found this useful in the following scenarios

  • Grouping like code blocks: constructors, fields, getters and setters, etc
  • Grouping code functionally: overloaded methods, transformations or mapping methods, CRUD methods
  • Test code: grouping test methods with blocks of data used by the test
  • Fixing IDE automatic code folding errors: Commonly seen in Python Code Editors

How do You Create a Custom Fold?

Unfortunately, there isn’t a single answer to this question that works universally across all the popular IDEs. However, I will share with you the method that works, out-of-the-box, with the JetBrains product suite, as well as provide some links to solutions I’ve found for other popular IDEs.

In the JetBrains products, we use the tag <editor-fold> </editor-fold>. Placing the opening and closing tags on different lines in front of a line comment. This will instruct IntelliJ, Pycharm, WebStorm, etc that the code between the tags can be folded. There is also an optional attribute desc="" that allows the developer to write a comment about the folded region that will be displayed when the code is folded.

code fold

Most IDEs have either some custom code folding mechanism built-in or a plugin available that will enable this behavior. The following links provide resources on how to enable custom code folding for VSCode and Eclipse.

Custom code folding has been around in IDEs for a while, but most developers have never come across it. I hope creating awareness of this tool will help you organize your code and keep your sanity.

Resources

Scroll to Top