If else too much? Watch me do it with Java 8!

Time:2021-7-22

Previously, I wrote a piece of logic in Java 8, which is similar to the following example:

/*
* official account: Java technology stack 
*/
if(xxxOrder != null){
	if(xxxOrder.getXxxShippingInfo() != null){
		if(xxxOrder.getXxxShippingInfo().getXxxShipmentDetails() != null){
			if(xxxOrder.getXxxShippingInfo().getXxxShipmentDetails().getXxxTrackingInfo() != null){
				...
			}
		}
	}
}

If you want to judge the values one by one, and then take the last values that are not empty, write in this wayifToo much is not elegant, so I use Java 8Optional.mapIt’s a way to get rid of layersif, colleagues call directly, do not understand, did not read can clickhereRead.

Recently, there is a strange demand. The general logic is as follows: if the value of a parameter is empty, take the values of several standby parameters in turn. If all the standby parameters are empty, take the default value at last.

For example: take the value of info. If info is empty, take the values of Info1, info2, info3 and info4 in turn. If all are empty, take the system default value.

The feeling is that it is completely opposite to the last scene. The last scene is to judge that it is not empty in turn and take the last value. This is to take the first value that is not empty.

Implementation scheme 1

useif/elseTo achieve:

/*
* official account: Java technology stack 
*/
String info = xx.getInfo();
if (info == null) {
    info = xx.getInfo1();
    if (info == null) {
        info = xx.getInfo2();
        if (info == null) {
            info = xx.getInfo3();
            if (info == null) {
                info = xx.getInfo4();
                if (info == null) {
                    Info = "Java technology stack (default)";
                }
            }
        }
    }
}

I bet someone will write like this. It’s not elegant. If there are many spare values, it’s not crazy..

Implementation plan 2

Of course, there is another way to write it

/*
* official account: Java technology stack 
*/
String info = null;
if (xx.getInfo() != null) {
    info = xx.getInfo();
} else if (xx.getInfo1() != null) {
    info = xx.getInfo1();
} else if (xx.getInfo2() != null) {
    info = xx.getInfo2();
} else if (xx.getInfo3() != null) {
    info = xx.getInfo3();
} else if (xx.getInfo4() != null) {
    info = xx.getInfo4();
} else {
    Info = Java technology stack;
}

This writing method is better than the first one, and it uses more writing methods.

Implementation scheme 3 (recommended)

The one above is also layeredifalsoelse ifIt’s not very elegant. It’s not recommended in many books, but it’s recommended

/*
* official account: Java technology stack 
*/
public String getInfo(XX xx)
    if (xx.getInfo() != null) {
        return xx.getInfo();
    } 
    
    if (xx.getInfo1() != null) {
        return xx.getInfo1();
    } 
    
    if (xx.getInfo2() != null) {
        return xx.getInfo2();
    } 
    
    if (xx.getInfo3() != null) {
        return xx.getInfo3();
    } 
    
    if (xx.getInfo4() != null) {
        return xx.getInfo4;
    } 
    
    Return "Java technology stack";
}

This is a slightly smarter way to write. It’s also a recommended way to write. You can extract a method separately and return it in turn to avoid too many errorsif/elseAnd lead to the possibility of potential logic confusion.

Implementation plan 4 (final recommendation)

Even so, I feel that the code is not very good-looking,ifThere are too many judgments. Let’s see how the stack leader can kill these with Java 8if/elseLet’s go!

Java 8 solution example:

/*
* official account: Java technology stack 
*/
List list = new ArrayList < > (arrays.aslist (info, Info1, info2, info3, info4, "Java technology stack (default)));
list.removeIf(StringUtils::isBlank);
String result = list.get(0);

3 lines, cool!!!

How is it achieved? We analyze it line by line

  • Build a list with each parameter in turn
  • Remove all empty parameters
  • Find the first parameter that is not empty

Using java 8 NEWremoveIfIt’s a clever way to get rid of itif/else, and can be usedLambdaIs expression or method reference very elegant?

I wanted to use itStreamIt’s all done by the party, but it’s helplessStreamCan’t receivenullParameter, otherwise pointer exception will be reported.

About this paragraphif/elseDo you know any other ways to improve logic? Welcome to share!

That’s all for this sharing. I hope it’s useful for you. I think it’s good. I’ll share it with you~

Official account official account official account of WeChat Java technology stack, the stack will continue to share the interesting Java technology. The public number is pushed for the first time. The public number can also be obtained from the menu in the history Java tutorial, all dry cargo.

Recommended by recent hot papers:

1.Java 15 officially released, 14 new features, refresh your cognition!!

2.Finally, I got the IntelliJ idea activation code through the open source project!

3.I use Java 8 to write a piece of logic, colleagues can not understand, you try..

4.The performance of undertow is very good!!

5.“Java Development Manual (Songshan version)” the latest release, download!

Feel good, don’t forget to like + forward!

Recommended Today

How to use Lamar in ASP. Net core

ASP. Net comes with a minimalist coreOut of the boxIn fact, you can also use third-party dependency injection containersDependency injection containerInstead of it, dependency injection is a design pattern that can effectively decouple objects and improve unit testing and maintainability. You can use itDependency injectionTo improve your code design, instead of new objects everywhere. Lamar […]