将具有相反操作数的两个函数重构为一个

Refactoring two functions with opposite operands into one

本文关键字:两个 函数 重构 一个 操作数      更新时间:2023-10-16

我想重构以下 2 个函数,以便逻辑将在一个具有一个参数的函数中:

void zoom_in() {
object.zoom_factor *= 2;
object.width /= 2;
object.height /= 2;
}
void zoom_out() {
object.zoom_factor /= 2;
object.width *= 2;
object.height *= 2;
}

我试图做什么:

void zoom_in() {
zoom_helper(true);
}
void zoom_out() {
zoom_helper(false);
}
void zoom_helper(bool in) {
float factor = (in ? 2 : .5);
object.zoom_factor *= factor;
object.width /= factor;
object.height /= factor;
}

但是,我宁愿让factor成为int.我可以干净地重构此代码吗?

您可以使用函数对象数组:

void zoom_helper(bool in) {
static const std::function<void(int&)> mul = [](int& x) { x *= 2; };
static const std::function<void(int&)> div = [](int& x) { x /= 2; };
static const auto update[2] = { div, mul };
update[in](object.zoom_factor);
update[!in](object.width);
update[!in](object.height);
}

不过,我认为这并没有多大好处,除了好玩之外,我不会亲自写这篇文章。

最简单的重构方法是使用if ... else块:

void zoom_helper(bool in) {
if (in) {
object.zoom_factor *= 2;
object.byte_aligned_columns /= 2;
object.rows /= 2;
}
else {
object.zoom_factor /= 2;
object.byte_aligned_columns *= 2;
object.rows *= 2;
}
}

但也许您正在寻找更"优雅"或"聪明"的东西?