Home > database >  What's more efficient, creating objects within a class or passing objects into class? [closed]
What's more efficient, creating objects within a class or passing objects into class? [closed]

Time:09-22

This example would have me create all motor objects within the global scope and pass them in.

#include <Motor.h>

Motor motor1;
Motor motor2;
Motor motor3;

class Axis
{
private:
    Motor _motor;
public:
    Axis(Motor motor)
    {
        _motor = motor;
        _motor.doStuff();
    }
};

Axis axis1(motor1);
Axis axis2(motor2);
Axis axis3(motor3);

or

This example would organize my motor objects into their respective axis objects.

#include <Motor.h>

class Axis
{
private:
    Motor _motor;
public:
    Axis()
    {
        Motor _motor;
        _motor.doStuff();
    }
};

Axis axis1;
Axis axis2;
Axis axis3;

I'm curious if there is performance differences. Also any notes about code maintainability are appreciated.

Added context, I'm writing C code to control a 5-DOF platform on an Arduino 2560Mega. I have 3 linear carriages with their own respective stepper motor and limit switches. Each stepper and 2 limit switches would make up an Axis class. My reason for making this class is the linear carriage has endpoints, and the motor & limit switches work together to determine them. I also have 2 servo motors rotating the platform. I'm contemplating making a System class that include the 3 Axes and Servos, so I could call a home method to move everything to an absolute home position and orientation. Plus, I'll need a method to move the platform to a given position and orientation from absolute home.

I'm a Mechanical Engineer in over his head, with mostly Python and MATLAB experience. Please forgive my shallow software knowledge.

CodePudding user response:

I think what's most professional is to use abstract base classes and dependency injection, and use a test driven approach. Build components first (e.g. motor with a motor interface abstract baseclass) test them and then combine them. https://en.wikipedia.org/wiki/Dependency_injection (e.g. https://www.developer.com/microsoft/dotnet/writing-more-testable-code-with-dependency-injection/), Though that might be a bit overkill for now ;)

CodePudding user response:

Maybe best is to use a dependency injection framework and let it create and inject the objects.

  • Related