When doing extract class refactorings the new sub- or helper-class requires a backreference to its creator and the creator needs a reference to its helper to make it accessible.
The issue with that structure is, that all those references have to be destructed manually which easily leads to memory leaks when one circular reference is forgotten to destruct.
Simplified Example:
function MasterClass(name) {
this.name = name;
this.extension = new MasterClassExtension(this);
}
function MasterClassExtension(masterClass) {
this.masterClass = masterClass;
}
MasterClassExtension.prototype.beautifiedName = function () {
return 'Beautiful ' + this.masterClass.name;
}
Usage:
new MasterClass('Tux').extension.beautifiedName(); // Returns "Beautiful Tux".
I know "Don't do work in constructor." but chose it for the sake of simplicity. Anyway, in an environment like PHP this does not matter as the process shuts down after the request is processed, but it does for continously running server structures like in Node.js or single page web apps.
Solution 1 Passing the reference any time.
var masterClass = new MasterClass('Tux');
MasterClassExtension.beautifiedName(masterClass); // Using singleton.
Pro:
Contra:
Solution 2 Destructing.
var masterClass = new MasterClass('Tux');
masterClass.extension.beautifiedName();
masterClass.destruct(); // Sets this.extension = null;
masterClass = null;
Pro:
Contra:
Solution 3 [???]
Is there a better solution / pattern / approach for solving this problem?
©2020 All rights reserved.