java:一长串条件,该怎么办? [英] java: A long list of conditions , what to do?

查看:143
本文介绍了java:一长串条件,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建议在Java中应用条件的正确方法。

I need suggestion for the right approach to apply conditions in Java.

我有100个条件,我必须根据这些条件更改String变量的值显示给用户。

I have 100 conditions based on which I have to change value of a String variable that would be displayed to the user.

示例条件: a< 5&& (b> 0&& c> 8)&& d> 9 || x!= 4

有更多条件,但变量或多或少相同。

More conditions are there but variables are the same more or less.

我现在正在这样做:

    if(condition1)
    else if(condition2)
    else if(condition3)
    ...

交换机案例替代方案显然是嵌套在if-else中,即

A switch case alternative would obviously be there nested within if-else's i.e.

if(condition1)
 switch(x)
  {
   case y:
     blah-blah
   }        
else if(condition2)
switch(x)
  {
   case y:
     blah-blah
   }  
else if(condition3)
...

但是我正在寻找一些更优雅的解决方案,例如使用具有多态支持的接口,我可以做些什么来避免代码行或什么应该是正确的方法。

But I am looking for some more elegant solution like using an Interface for this with polymorphic support , What could be the thing that I could possibly do to avoid lines of code or what should be the right approach.


---编辑---

---Edit---







我在Android设备上需要这个。但它更像是一个java构造。

这是我对我的条件的一个小快照。如果一些是正确的,将添加更多。这显然需要更多的if-else,而且那些也可以嵌套。在这种情况下,处理会变慢。


我现在将消息存储在单独的类中我保持静态的各种字符串变量,所以如果条件变为真
然后我从唯一的类中选择静态变量并显示
一。这对于存储结果消息是否正确。


推荐答案

取决于条件输入的数量,您可以使用查找表,甚至 HashMap ,通过在单个值中编码所有输入甚至一些相对简单的复杂条件:

Depending on the number of conditional inputs, you might be able to use a look-up table, or even a HashMap, by encoding all inputs or even some relatively simple complex conditions in a single value:

int key = 0;

key |= a?(1):0;
key |= b?(1<<1):0;
key |= (c.size() > 1)?(1<<2):0;
...

String result = table[key]; // Or result = map.get(key);

此范例具有恒定时间的附加优势( O(1))复杂性,在某些情况下可能很重要。根据条件的复杂程度,您甚至可能在代码路径中平均拥有更少的分支,而不是完整的 if-then-else spaghetti代码,可能会带来性能提升。

This paradigm has the added advantage of constant time (O(1)) complexity, which may be important in some occasions. Depending on the complexity of the conditions, you might even have fewer branches in the code-path on average, as opposed to full-blown if-then-else spaghetti code, which might lead to performance improvements.

如果您在问题中添加了更多上下文,我们可能会为您提供更多帮助。条件输入来自哪里?他们喜欢什么?

We might be able to help you more if you added more context to your question. Where are the condition inputs coming from? What are they like?

更重要的问题是:什么是您要解决的实际问题?

这篇关于java:一长串条件,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆