How to avoid excessive if else in code

Source: Internet
Author: User
Tags switch case

If else is really much in development
Just hit the code, looked down and found n more than if else ah
I hope we can give you a good suggestion.

--------

Use pattern, such as chain of responsibility

--------

Enum

--------

I'm here to pick up the points, the inevitable logical judgment, the writing is still to be written

--------

It's upstairs. It is not possible to use an enumeration if you have an if to judge an enumeration value.

This looks at the business needs. If the business conditions are already more. I think it's inevitable that there will be more.

--------

1, can use the condition ternary operator time as far as possible, but the business logic may not see clearly

2, can use the switch when possible

3, more use if{return; ... if{return; ... struct, or while (true) {if {break;} .. if {break;} .. break; Structure (for inconvenient exit of the whole method, but there is a dead loop risk, the code is accustomed to good use), branching conditions clear, multi-layer nesting if...else ... Most likely to make mistakes

4, as far as possible partition method, let If...else ... There's only one method call, and the logic is clear.

Currently used so much, the landlord can refer to.

--------

Enumerations can have their own methods, and the implementation of each method can be different, of course, the enumeration is not omnipotent, but also can solve a part of the problem

Using switch or enum, if the project is large or involves the rationality of the system, use design pattern is also a good choice, such as the responsibility chain design mode: http://4ujava.javaeye.com/blog/547166

--------

Logically important, there is no way of things if () else if ()

--------

is swing or the Web Oh ....

--------

If you want to extract all the If else logic, consider using the rule engine

Ilog,drools these are to take the complex business logic through the way of configuration file, later change or even add new business logic without changing the code, change the configuration file can

--------

Without if else, you can only use if return ...

--------

I know the way to avoid ifelse:
The first is table-driven: It's just a matter of storing all the possible data in the first place.
The second is to use the state/policy mode
The specific way to do that is to see what you want to achieve the function of ....

--------

Why don't you like if-else ...

In general, use a while instead of an if statement, especially if there are many if statements

There are some flaws in the IF statement relative to the while statement. Therefore, it is recommended to consider using the while statement more.

--------

If else is very common, why not use if else? Do you always do boolean operations?
If you say, because if else is a lot, you can consider using listener mode to put logical judgments into several listeners, each listener handling a situation where data comes in to all listeners until someone processes it.

In essence, if else

It depends on your purpose.

--------

With Swith

--------

With A?B:C format, the function is equivalent to If-else, the format is simple, recommend ~ ~

If

Return

Give it a try.

--------

If
Return

Switch
Case

--------

Switch, but Java switch seems to support only int and Char

And we can use relational computing in discrete mathematics to simplify or combine conditions.

--------

Using switch or enum, if the project is large or involves the rationality of the system, use design pattern is also a good choice, such as the responsibility chain design mode: http://4ujava.javaeye.com/blog/547166
Responsibility chain design mode is not to the if else encapsulation up, not too clear, hehe, beginner. And the avatar is good.

If you are afraid if else nesting more confusion, in addition to using the mode of these methods, I think you can write the logic of the conditions of a small private method, as follows: Java code

if (a) {DOA ();} else if (b) {DoB ();} else {DoC ();} DoA () {} DoB () {} DoC () {}



This seems to be a little bit clearer and hopefully it will help you. Good luck!

--------

Is this possible?
Without if, what the world would be like.

--------

Reasonable business planning, really need to use. Why bother about this?

-------

Reasonable business planning, really need to use. Why bother about this?

Some people can't see the sand in their eyes.
But writing code should pursue as short and short as possible.
Beautiful structure

--------

Use pattern, such as chain of responsibility


Yes, it's a model.

--------

It's just a little annoying to watch.
If if else feels like writing code in the same way as in school
It just doesn't seem like it.

--------

Without if else, I might not be able to write a program.

--------

Take forum posts for example, such as Forummessage is a model, but the actual post is divided into two natures: Theme Stickers (the first root post) and replies (back to previous posts), here is a simple solution:
Build a forummessage and then join Istopic in forummessage to make judgments like this, and note that your introduction of a simple attribute here may cause your program to have other places where if else is judged.
If we use another analysis to realize the idea of the concept of the object, in fact, there are theme posts and replies, is two objects, but the two objects are mostly consistent, so I set forummessage as the expression theme And then create a subclass of inherited Forummessage Forummessagereply as a reply, so that I am in the program place, such as service, I have confirmed that this model is a reply, I will be directly traced back to Forummessagereply can, This is kind of like a forced type conversion when you put an object in and out of a collection. By this means I have eliminated the possibility that the judgment statement of if else in the program will appear.
--------

How is the value of the body, you can use Swith () {case:
//.....
break;
Replace

---------

It is also possible to use if else in a small place, such as a simple numerical judgment, which is generally used in design mode when implementing business functions. If you've done a lot of systems and haven't used if else for a long time, then you might actually be in the OO design situation.

--------

It's a matter of personal habits, and when you write code, it's okay to align if ELSE.

--------

I've heard people say that if you have a lot of if...else in your code, it means your code is not good for the object. Perhaps it is superficial, I still think if and else are logical judgments must be. A few brothers upstairs said, replace with switch, individual and if. There is no essential difference.

--------

Use it when it's time to use it. ~

--------

Refactor to state mode.

--------

You can post your code and get everyone to give it to you. In fact, sometimes because of the repetitive judgment of conditions, there are really a lot of damned if else combinations. Write it as you write it. When you're done, I want you to look at it in a different light. This code is not rigorous.

--------

In the project it is less to use the dot if else but sometimes it has to be used or a dot. Logical question of time. But you can use design patterns to try out the plan. The main thing is to have a clear structure.

--------

I've heard people say that if you have a lot of if...else in your code, it means your code is not good for the object. Perhaps it is superficial, I still think if and else are logical judgments must be. A few brothers upstairs said, replace with switch, individual and if. There is no essential difference.


Yes, the code has been working for 2 years. Can you find code or if else ah, it looks like a lot of fun.
Everyone has a good way to say it again.

--------

good at using return;
Some if statements may not need else. Some if statements are judged to be set up and can be returned directly without the need to go down.
In fact, if else is irreplaceable in other languages, you sometimes have to use it.
I remember that the switch case seems to have only an int type as an argument.
--------

good at using return;
Some if statements may not need else. Some if statements are judged to be set up and can be returned directly without the need to go down.
In fact, if else is irreplaceable in other languages, you sometimes have to use it.
I remember that the switch case seems to have only an int type as an argument.

int and Char
--------

You can use the switch when not if...else ah, more efficient.

--------

It is not recommended to use too many if else, switch. Because of poor scalability, and difficult to maintain.

You can try using polymorphic

--------Java Code

Package com.csdn; Interface Animal {void speak ();} class Dog implements Animal {@Override public void speak () {System.out.println ("Dog Speak. " ); } } Class Cat implements Animal {@Override public void speak () {System.out.println ("Cat speak.");}} class Pig implemen TS Animal {@Override public void speak () {System.out.println ("pig speak.");}, public class Noifelse {//For example, there's a requirement now. ,//By State to judge that animal called//0 let the dog bark, 1 Let the cat, 2 let the pig called/** * Method 1/private void animalspeak (int state) {animal[] animals = {New Dog ( ), New Cat (), New Pig ()}; Animals[state].speak (); /** * Method 2, there is no use of the animal interface/private void ANIMALSPEAK2 (int state) {if (state = = 0) {new Dog (). speak ();} if (state = 1 {New Cat (). speak ();} if (state = = 2) {new Pig (). Speak ()}} public static void Main (string[] args) {Noifelse t = new Noifelse (), int state = 1; t.animalspeak (state); (state); } }



LZ Comparison Method 1 and Method 2

--------

The conditions of judgment can not be avoided, at best, only to replace the form.
If else doesn't matter.! But try not to nest, nested more than you have to set the dizzy.
LS's said if return is a better way to avoid nesting solutions!

--------

Must be a matter of business logic .... May be the business logic design is not reasonable. ~

--------

Design pattern:
Switch with adapter


Design Patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.