JSPM

safe-init-destroy

2.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q17664F
  • License Apache-2.0

The right way to write `destroy()` functions

Package Exports

  • safe-init-destroy
  • safe-init-destroy/main.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (safe-init-destroy) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

safe-init-destroy

If you have a function called destroy (or deinit) and it is longer than 3 lines, you may want to rewrite it using this approach.

Example

Before After
// ...





function init() {
  doSomething();

  // ...
  doSomethingElse();

  // ...
  if (cond) {
    doSomeOtherThing();

  }
}
function destroy() {
  undoSomething();
  undoSomethingElse();
  if (didDoSomeOtherThing) {
    undoSomeOtherThing();
  }
}
// ...
// ...
+const {
+  onDestroy,
+  destroy
+} = createDestructionManager();
 
 function init() {
   doSomething();
+  onDestroy(() => undoSomething());
   // ...
   doSomethingElse();
+  onDestroy(() => undoSomethingElse());
   // ...
   if (cond) {
     doSomeOtherThing();
+    onDestroy(() => undoSomeOtherThing());
   }
 }
-function destroy() {
-  undoSomething();
-  undoSomethingElse();
-  if (didDoSomeOtherThing) {
-    undoSomeOtherThing();
-  }
-}
 // ...

Such code is much more maintainable because all the related things are grouped together. If you change one piece of code, you won't forget to update its corresponding destroy() part (or vice versa), because it's immediately next to it (perhaps even inside the same nested code block).

Feedback wanted

I would like to hear feedback on this approach. I don't know why I havent's seen it implemented in the wild, yet I have seen bloated destroy methods that look like they can break from a breath of wind (no offence). If you have seen similar code (even in different languages), or code that solves the same problem, or code that manages to avoid this problem, please let me know.