我正在为大型应用编写代码,并且有一个事件需要进行大量if
/ else
次检查。
例如:
if (i == 1) { /* some logic */ }
else if (i == 2) { /* some logic */ }
// ...
// ...
else if (i == 1000) { /* some logic */ }
有没有更有效或有组织的方式来写这个?
答案 0 :(得分:3)
使用switch语句。 防爆。
switch(variable) {
case 1:
//DoStuff
break;
case 2:
//DoStuff
break;
default:
//Dostuff
break;
}
或者,如果您知道最常见的情况,可以从那里分解以改进算法运行时间,这可能需要采用不同的方法。
答案 1 :(得分:2)
听起来你有一系列功能,你只需要使用HashMap
。 i
将是地图的索引。哈希映射非常有用,因为它们可以快速找到密钥的相应值,而无需在找到匹配项之前比较大量值。
以下是HashMap
到Any
的{{1}}示例。因为Scala支持元组,所以这是一个完全通用的解决方案。
Any => Any
这是输出:
object Hello extends App {
import scala.collection.immutable
type F1 = (Any) => Any
val hashMap: immutable.Map[Int, F1] =
immutable.HashMap[Int, F1](
1 -> { (a: Int) => a * 2 }.asInstanceOf[F1], // Function literal that doubles it's input
2 -> { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
1000 -> { (_: Unit) => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
)
def lookup(i: Int, args: Any): Any = hashMap(i)(args)
def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")
report(1, 21)
report(2, ("word ", 5))
report(1000, ())
}
更新:这是一个使用数组的版本。请注意,此版本的索引必须从0开始,而不是之前的任意数字:
1: 42
2: word word word word word
1000: The date and time is Sat Dec 23 19:45:56 PST 2017
输出是:
object Hello2 extends App {
type F1 = (Any) => Any
val array: Array[F1] =
Array[F1](
{ (a: Int) => a * 2 }.asInstanceOf[F1], // Function literal that doubles it's input
{ (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
{ (_: Unit) => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
)
def lookup(i: Int, args: Any): Any = array(i)(args)
def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")
report(0, 21)
report(1, ("word ", 5))
report(2, ())
}
答案 2 :(得分:1)
如果你在这些代码块中做了1000个不同的事情,那么问题就是逻辑复杂性。在这种情况下,您别无选择,只能像这样编码或更改为switch
。
在if
的情况下,唯一要记住的关键是将您认为最有可能/频繁的案例移到最顶层。
如果您不做1000件不同的事情,必须单独编码,那么您可以考虑其中一些选项:
如果可能的话,分解成范围:
if(i < 300): {
//do something
} else if(i < 600) {
// do another thing
}
//do the default thing
如果可以编程逻辑并且i
的值可以用作决定实现逻辑的参数,那么你可以使用抽象:
abstract class NumberProcessor {
protected int i;
static NumberProcessor getInstance(int i){
//Use this block to look at the number and choose one of few implementations...
//and store number in the instance
}
abstract void processNumber();
}
然后,您可以根据您可以分组的逻辑编写一些实现。