An open API service indexing awesome lists of open source software.

https://github.com/wofwca/safe-init-destroy

The right way to write `destroy()` functions
https://github.com/wofwca/safe-init-destroy

async constructor deinit destroy destructor init library observer-pattern refactoring utils

Last synced: 11 months ago
JSON representation

The right way to write `destroy()` functions

Awesome Lists containing this project

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.

> 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



```js
// ...

function init() {
doSomething();

// ...
doSomethingElse();

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

}
}
function destroy() {
undoSomething();
undoSomethingElse();
if (didDoSomeOtherThing) {
undoSomeOtherThing();
}
}
// ...
```

```diff js
// ...
+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.