java: A long list of conditions , what to do? [clo

2020-07-09 10:04发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 7 years ago.

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

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

an example condition: a<5 && (b>0 && c>8) && d>9 || x!=4

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

I am doing this right now:

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

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---


I actualy require this on an android device. But its more of a java construct here.

This is a small snapshot of conditions that I have with me. More will be added if a few pass/fail. That obviously would require more if-else's with/without nesting. In that case would the processing go slow.

I am as of now storing the messages in a separate class with various string variables those I have kept static so if a condition gets true then I pick the static variable from the only class and display that one. Would that be right about storing the resultant messages.

回答1:

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);

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?

And the more important question: What is the actual problem that you are trying to solve?



回答2:

There are a lot of possibilities to this. Without knowing much about your domain, I would create something like (you can think of better names :P)

 public interface UserFriendlyMessageBuilder {
      boolean meetCondition(FooObjectWithArguments args);

      String transform(String rawMessage);
 }

In this way, you can create a Set of UserFriendlyMessageBuilder and just iterate through them for the first that meets the condition to transform your raw message.

public class MessageProcessor {
    private final Set<UserFriendlyMessageBuilder> messageBuilders;

    public MessageProcessor(Set<UserFriendlyMessageBuilder> messageBuilders) {
        this.messageBuilders = messageBuilders;
    }

    public String get(FooWithArguments args, String rawMsg) {

        for (UserFriendlyMessageBuilder msgBuilder : messageBuilders) {
            if (msgBuilder.meetCondition(args)) {
                return msgBuilder.transform(rawMsg);
            }
        }
        return rawMsg;    
    }
}


回答3:

What it seems to me is "You have given very less importance to design the product in modules" Which is the main factor of using OOP Language.

eg:If you have 100 conditions and you are able to make 4 modules then therotically for anything to choose you need 26 conditions.



回答4:

This is an additional possibility that may be worth considering.

Take each comparison, and calculate its truth, then look the resulting boolean[] up in a truth table. There is a lot of existing work on simplifying truth tables that you could apply. I have a truth table simplification applet I wrote many years ago. You may find its source code useful.

The cost of this is doing all the comparisons, or at least the ones that are needed to evaluate the expression using the simplified truth table. The advantage is an organized system for managing a complicated combination of conditions.

Even if you do not use a truth table directly in the code, consider writing and simplifyin one as a way of organizing your code.