Closed
Description
Hello,
I open this issue to discuss about the Finalizers and the main concept of destructors. Finalizers smell like a small bandage on top of the language. The C++ language have the destructor concept which is (for me) cleaner, easier to use/understand and achieve if i'm not wrong the exact same behavior.
What are the benefits for Dart to use Finalizers instead of something like destructors ?
The usage feel a bit over complexe for a simple feature (maybe not technicaly, sorry !)
To use Finalizer in dart :
We need to :
- define a static Finalizer
- attach the Finalizer in constructor
- detach the Finalizer in the close method
class Database {
// Keeps the finalizer itself reachable, otherwise it might be disposed
// before the finalizer callback gets a chance to run.
static final Finalizer<DBConnection> _finalizer =
Finalizer((connection) => connection.close());
final DBConnection _connection;
Database._fromConnection(this._connection);
factory Database.connect() {
// Wraps the connection in a nice user API,
// *and* closes connection if the user forgets to.
final connection = DBConnection.connect();
final wrapper = Database._fromConnection(connection);
// Calls finalizer callback when `wrapper` is no longer reachable.
_finalizer.attach(wrapper, connection, detach: wrapper);
return wrapper;
}
void close() {
// User requested close.
_connection.close();
// Detach from finalizer, no longer needed.
_finalizer.detach(this);
}
}
To use destructor In c++ :
We need to :
- define the destructor
class Database {
public:
Database() : _connection(new DBConnection()) {}
void close() {
if (_connection) {
_connection->close();
delete _connection;
_connection = nullptr;
}
}
~Database() {
close();
}
private:
DBConnection* _connection;
};
If i'm not wrong other language like Rust, Python, Swift, Objective-C, PHP follow this way.
Why Dart don't use it ?
Metadata
Metadata
Assignees
Labels
No labels