Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid code duplication with function overloading

I have a pair of overloaded functions:

void func(const std::string& str, int a, char ch, double d) {
    // piece of code A
    sendMsg(str, a, ch, d);
    // piece of code B
}

void func(int a, char ch, double d) {
    // piece of code A
    sendMsg(a, ch, d);
    // piece of code B
}

piece of code A and piece of code B are exactly the same, the only difference is the parameter of sendMsg.

Is there some way to avoid the code duplication?

like image 840
Yves Avatar asked Aug 04 '21 07:08

Yves


People also ask

How do you avoid code duplication?

Don't Repeat Yourself (DRY): Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.

How to avoid code duplication in c++?

The C++11 delegating constructors reduce the code duplication and make effective use of the member initializer lists.

How do I stop code duplication in HTML?

If you want to keep a consistent html structure for the sidebar on each page, use php. You would create a file called sidebar. php, and use the include method to import the same code into each page. If you want to change it later, edit the single sidebar.


Video Answer


3 Answers

template may be a possibility:

template <typename ... Ts>
auto func(const Ts&... args)
-> decltype(sendMsg(args...), void()) // SFINAE to only allow correct arguments
{
    // piece of code A
    sendMsg(args...);
    // piece of code B
}

but moving // piece of code A in its own function would probably be my choice.

like image 123
Jarod42 Avatar answered Oct 14 '22 00:10

Jarod42


You would have to do something like

void codeA() {
    // ...
}

void codeB() {
    // ...
}

void func(const std::string& str, int a, char ch, double d) {
    codeA();
    sendMsg(str, a, ch, d);
    codeB();
}

void func(int a, char ch, double d) {
    codeA();
    sendMsg(a, ch, d);
    codeB();
}
like image 8
Tzig Avatar answered Oct 13 '22 22:10

Tzig


Another idea would be to give a default value to str:

void func(int a, char ch, double d, const std::string& str = "")
{
    // piece of code A
    if (str.empty()) sendMsg(a, ch, d);
    else sendMsg(str, a, ch, d);
    // piece of code B
}
like image 6
mfnx Avatar answered Oct 14 '22 00:10

mfnx