Search code examples
javascriptscopecommentsdocumentation

using block scopes to organize complex code


I am building a three.js library and found placing comments and nesting content below the comment in {} made it easy to navigate lots of code. I was wondering if there are other better ways to do this.

Why I would like to do this

  1. the main reason: I can quickly collapse code based on the comments I see above the block scopes. Thereby making it easy to focus on the code I want to change.

  2. I'd only use this in the class initialisation, or very complex methods. Or rather, any areas where there is significant code use with applicable labels for those areas.

  3. I would never scope a section without an appropriate comment accompanying it.

  4. This helps me scale these different sections, especially if they are not something that would scale into a new class or object within reason

  5. Im aware a common problem with code bases is they can be extremely overwhelming, especially when learning them. I think this way of organising code could help make it more approachable and less overwhelming to look at

  6. I would love if there was a feature in IDE's to do something like this

Example of its use:

Collapsed: enter image description here

Un-collapsed:

enter image description here

Collapsed:

enter image description here

Un-collapsed

enter image description here

I also see this as a compliment to refactoring, whether it's abstracting into functions or more classes. This seems to be agile and deals with uncertainty in the code base especially if you need to neatly layer problems solutions into themselves in ways that would not qualify a new class, or new method.


Solution

  • I would say it's better to break down into separate functions. Adding unnecessary blocks could have surprising consequences for future maintainers. Many editors support using a special syntax within comments to aid code folding and navigation without altering the syntax tree.

    [Edit] Whilst I am really an Emacs-only guy (TM), the docs (https://code.visualstudio.com/docs/editor/codebasics) for Vscode suggest something along the lines of

    //#region