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
- Host: GitHub
- URL: https://github.com/wofwca/safe-init-destroy
- Owner: WofWca
- License: apache-2.0
- Created: 2022-12-20T18:12:57.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2023-04-25T14:32:49.000Z (almost 3 years ago)
- Last Synced: 2025-03-02T01:40:02.151Z (12 months ago)
- Topics: async, constructor, deinit, destroy, destructor, init, library, observer-pattern, refactoring, utils
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/safe-init-destroy
- Size: 14.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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.