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?
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.
The C++11 delegating constructors reduce the code duplication and make effective use of the member initializer lists.
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.
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.
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();
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With