Skip to content

WofWca/safe-init-destroy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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.

UDP: I just learned that this is an "observer" design pattern, so I guess the takeaway is "the observer pattern is good in this case".

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.