node icon indicating copy to clipboard operation
node copied to clipboard

Refactor C-style function types to std::function for improved type safety and readability

Open edilson258 opened this issue 8 months ago • 2 comments

Description:

In several places within the codebase, C-style function pointer definitions are still being used. While these work, they do not provide the same level of type safety, and readability as C++'s std::function. Refactoring these instances to use std::function will:

  1. Improve Type Safety: std::function provides better type checking at compile-time, reducing the chance of mismatched function signatures.
  2. Increase Readability: std::function allows for clearer, more expressive code, particularly when dealing with complex function signatures.
  3. Enhance Flexibility: std::function can easily bind to lambdas, member functions, and function pointers, providing a more flexible interface compared to raw function pointers.

Tasks:

  • Identify and locate instances of C-style function pointer definitions.
  • Refactor to use std::function with appropriate type signatures.
  • Ensure that all relevant code maintains functionality after the refactor.

Example:

If the current code uses a C-style function pointer like:

void (*callback)(int);

It could be refactored to this

std::function<void(int)> callback;

edilson258 avatar Apr 26 '25 12:04 edilson258

(1) and (2) are debatable, (3) is mostly irrelevant - libraries like libuv and openssl don't take fat pointers, you can't pass closures to them.

bnoordhuis avatar May 04 '25 09:05 bnoordhuis

@edilson258 I noticed that you also posted this on the discord server (discord message)

@RafaelGSS replied with:

I wouldn’t do it until we find some clear benefits

std::function is a heavy C++ abstraction. It generates more template instantiations (more symbols, larger binary), whereas function pointers are minimal.

Node.js sometimes interacts closely with pure C libraries (e.g., OpenSSL, uv, c-ares). std::function cannot be passed to C APIs without special wrapping, while raw pointers are compatible.

(which is in line with @bnoordhuis' comment above)

and you agreed with them.

So I would imagine that we can just close this issue since everyone seems to be in agreement that the current definitions are ok, do you agree? 🙂

dario-piotrowicz avatar May 04 '25 15:05 dario-piotrowicz