Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid mistakes in functions with same type arguments

How can I avoid mistakes with passing parameters of same type to function?

Let's consider function reading some binary data:

std::vector<uint8_t> read(size_t offset, size_t amount);

It's so easy to mistake offset with amount(I did similar it many times).

I see solution to this:

struct Offset
{
    explicit Offset(size_t value) : value{value}{}
    size_t value;
};
struct Amount
{
    explicit Amount(size_t value) : value{value}{}
    size_t value;
};
std::vector<uint8_t> read(Offset offset, Amount amount);

Is there a better solution to avoid mistakes like that?

like image 646
MamCieNaHita Avatar asked Oct 25 '25 06:10

MamCieNaHita


1 Answers

Another thing that you can do is to pass parameters in a structure. This also allows you to set sensible defaults for the values. This is especially useful when a constructor takes a large number of arguments. For example:

class FooService
{
public:
    // parameters struct.
    struct Options
    {
        ip::address listen_address = ip::address::any();
        uint16_t port = 1337;
        bool allow_insecure_requests = false;
        std::string base_directory  = "/var/foo/"
    };
    //constructor takes the options struct to pass values. 
    explicit FooService(FooServiceOptions options);
    // ...
};

Which is then used like:

FooService::Options o;
o.port = 1338;
//all other values keep their defaults. 

auto service = make_unique<FooService>(o);
like image 165
Paul Belanger Avatar answered Oct 26 '25 21:10

Paul Belanger