2.0.1 • Published 1 year ago

safe-init-destroy v2.0.1

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 year ago

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

// ...





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.