[英]Refactoring two functions with opposite operands into one
I would like to refactor the following 2 functions so that the logic will be in one function with one parameter:我想重构以下 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;
}
What I tried to do:我试图做的事情:
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;
}
However I would rather have the factor
be an int
.但是,我宁愿将
factor
设为int
。 Can I cleanly refactor this code?我可以干净地重构这段代码吗?
You can use an array of function objects:您可以使用一组函数对象:
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);
}
I don't think this is much of a benefit though, and I would not personally write this except for fun.我不认为这有什么好处,除了好玩之外,我不会亲自写这个。
The simplest way to refactor is just using an if ... else
block:最简单的重构方法是使用
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;
}
}
But maybe you're looking for something more 'elegant' or 'clever'?但也许您正在寻找更“优雅”或“聪明”的东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.