gz-sensors
gz-sensors copied to clipboard
Proposal: Use RAII/Constructor to initialize sensors instead of Init() pattern
Original report (archived issue) by Michael Grey (Bitbucket: mxgrey, GitHub: mxgrey).
Functions like Init()
and Load()
which have to be called after construction can be confusing for users (and developers), and easily lead to bugs and maintenance issues. As an example, it can be very unclear whether Init()
should be called before or after Load()
, or it might not be obvious to a user that these functions even exist, and so they might try to use the constructed object in an uninitialized (or partially initialized) state, leading to crashes or exceptions that are difficult to debug.
If it's at all possible, I would strongly encourage us to design sensors so that the arguments that get passed to Init()
and Load()
would instead get passed to the constructor of the Sensor
. Classes that derive from Sensor
therefore must make constructors which accept those same arguments (plus they have the option of additionally accepting their own custom arguments).
We could keep the Load(sdf)
function in case we want a way to re-initialize a sensor or change its parameters while it's in operation, but calling it would be optional. The Init()
function would be removed entirely.
I believe we're going to be aggressively enforcing the RAII pattern in the ign-physics
design, so it would be especially great if ign-sensors
were able to match that.
Original comment by Michael Grey (Bitbucket: mxgrey, GitHub: mxgrey).
Alternatively, if for some reason it's not possible or not desirable to put all initialization in the constructor, I would recommend we make the constructors protected/private and use something like a factory pattern to produce them. The user/developer would not be able to construct a sensor in an uninitialized state, and the factory would be responsible for ensuring that it is fully initialized before being provided to a user/developer.