我正在为大型应用程序编写代码,并且有一个事件需要大量的if
/ else
检查。
例如:
if (i == 1) { /* some logic */ }
else if (i == 2) { /* some logic */ }
// ...
// ...
else if (i == 1000) { /* some logic */ }
是否有更有效或有组织的方式来写这个?
听起来你有一系列功能,你只需要使用HashMap
。 i
将成为地图的索引。哈希映射很有用,因为它们可以快速找到密钥的相应值,而无需在找到匹配项之前比较大量值。
这是一个从HashMap
到Any
的Any => Any
的例子。因为Scala支持元组,所以这是一个完全通用的解决方案。
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, ())
}
这是输出:
1: 42
2: word word word word word
1000: The date and time is Sat Dec 23 19:45:56 PST 2017
更新:这是一个使用数组的版本。请注意,此版本的索引必须从0开始,而不是之前的任意数字:
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, ())
}
输出是:
0: 42
1: word word word word word
2: The date and time is Sat Dec 23 20:32:33 PST 2017
使用switch语句。防爆。
switch(variable) {
case 1:
//DoStuff
break;
case 2:
//DoStuff
break;
default:
//Dostuff
break;
}
或者,如果你知道最常见的情况,你可以从那里分解它以改进算法运行时间,这可能需要不同的方法。
如果您在这些代码块中执行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();
}
然后,您可以根据可以分组的逻辑编写一些实现。