Is It a Good Idea to Provide Different Function Signatures for the Same Task?

cclass-designcoding-stylefunctionsreadability

Here is a C++ class that gets constructed with three values.

class Foo{

    //Constructor
    Foo(std::string, int, char);

private:
    std::string foo;
    char bar;
    int baz;
};

All of the parameter types are different.
I could overload the constructor so that order doesn't matter.

class Foo{

    //Constructors
    Foo(std::string, char, int);
    Foo(std::string, int, char);
    Foo(char, int, std::string);
    Foo(char, std::string, int);
    Foo(int, std::string, char);
    Foo(int, char, std::string);


private:
    std::string foo;
    char bar;
    int baz;
};

But is that a good idea?
I started doing it because I knew what things a class/function needed;
I didn't always remember what order it took them in.


I've been assuming that the compiler optimizes this as if I called the same constructor.

//compiler will implement this with the same code? 
//maybe not.. I could call a function to get a parameter, 
//and that function could change the state of the program, before calling
//a function to get another parameter and the compiler would have to
//implement both
Foo foo1("hello",1,'a');
Foo foo2('z',0,"world");

What are your opinions on overloading a function so that the order doesn't matter?


Also, If I'm writing some utility functions,
Is it a good idea to provide different function names that do the same thing?

eg.

void Do_Foo();
void DoFoo();
void do_foo();
//etc..

I don't often see these two but similar conventions.
Should I break or embrace the habit?

Best Answer

I could overload the constructor so that order [of the parameters] doesn't matter... But is that a good idea?

No.

Having different constructor overloads will have the opposite effect of what you are intending. The programmer coming after you expects different overloads to have different behavior, and will ask: "What sort of different behavior is being expressed by each of these overloads?

Most programmers expect the discipline of having method parameters in a predefined order, and tools like IntelliSense will tell them the expected order of the parameters as they enter them.


Having multiple function names that do the same thing is the same problem; programmers expect the variants to have different behavior. One function or method per behavior, please, and just adopt a consistent naming pattern.