如何以更优雅的方式对这些条件语句进行编码可扩展方式 [英] How to code these conditional statements in more elegant & scalable manner
问题描述
在我的软件中,我需要基于2个参数来确定功能的版本.例如.
In my software, I need to decide the version of a feature based on 2 parameters. Eg.
Render version 1 -> if (param1 && param2) == true;
Render version 2 -> if (!param1 && !param2) == true;
Render version 3 -> if only param1 == true;
Render version 4 -> if only param2 == true;
因此,为了满足此要求,我编写了如下代码-
So, to meet this requirement, I wrote a code which looks like this -
if(param1 && param2) //both are true {
version = 1;
}
else if(!param1 && !param2) //both are false {
version = 2;
}
else if(!param2) //Means param1 is true {
version = 3;
}
else { //Means param2 is true
version = 4;
}
肯定有多种编码方法,但是我尝试了不同的方法后最终确定了此方法,因为这是我能想到的最易读的代码.
但是这段代码绝对不可扩展,因为-
There are definitely multiple ways to code this but I finalised this approach after trying out different approaches because this is the most readable code I could come up with.
But this piece of code is definitely not scalable because -
- 让我们说明天我们要引入一个称为param3的新参数.然后
没有支票的数量会增加,因为可能有多个
组合.
- 对于此软件,我非常确定我们 将来将不得不容纳新的参数.
- Let say tomorrow we want to introduce new param called param3. Then
the no. of checks will increase because of multiple possible
combinations.
- For this software, I am pretty much sure that we will have to accommodate new parameters in future.
可以有任何可扩展的&可读的方式编写这些要求的方法?
Can there be any scalable & readable way to code these requirements?
推荐答案
如果必须枚举所有可能的布尔值组合,将它们转换成数字通常是最简单的:
If you have to enumerate all the possible combinations of Booleans, it's often simplest to convert them into a number:
// param1: F T F T
// param2; F F T T
static final int[] VERSIONS = new int[]{2, 3, 4, 1};
...
version = VERSIONS[(param1 ? 1:0) + (param2 ? 2:0)];
这篇关于如何以更优雅的方式对这些条件语句进行编码可扩展方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!