将具有相反操作数的两个函数重构为一个
Refactoring two functions with opposite operands into one
我想重构以下 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;
}
}
但也许您正在寻找更"优雅"或"聪明"的东西?
相关文章:
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 如何比较两个函数的速度和性能
- 如何在构造器的成员初始值设定项列表中调用两个函数?
- 如何将这两个函数组合成一个实现?
- 将具有相反操作数的两个函数重构为一个
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 具有相同主体的两个函数具有不同的名称
- 通过作为类的公共成员的两个函数将函数作为参数传递
- 如何使用排序和比较这两个函数在 c++ 中对字符数组进行排序?
- 是否可以在C++中将两个函数一起添加
- C++ 两个函数除了一行之外执行相同的操作
- 如何编写连接两个函数的函数
- 如何执行两个函数参数具有相同的模板类型
- 当两个函数位于一行中时,堆栈框架的样子
- 为什么这两个函数的行为不同
- 为什么当我有两个函数时编译器没有显示错误,一个将采用基类,一个将派生类作为参数
- 系统堆栈中的两个函数的递归调用(将不同数量的数组作为参数传递)有什么区别
- 如何在一个构造函数中使用两个可变参数模板参数来绑定两个函数
- 如何在c++中的两个函数中传递对象的同一实例