[Java] Optional memorandum

Optional that has nothing to do with legacy code

I've been happy to use it for the first time recently, so it's a memo of the usage example so that I can use it again.

I am enrolled in a field where Java 1.6 may be forced for a completely new project in 2019. I haven't had many opportunities to come into contact with Java 8 during this period. Under such circumstances, I wrote it with the information I heard when Java 8 appeared, "It seems that null check can be easily written from Java 8." I have checked and written on multiple sites, but if you have any suggestions for improvement or Masakari, please leave a comment. (Because there is no reviewer who can review my code in the case) (I am reviewing other members)

About get

I don't use it because I didn't know where to use it. When I looked at some sites, I saw "Don't use get ", so I think it was the correct answer. There is a feeling.

Caution

"Optional can simply replace the traditional null check" was not the correct perception. "Optional can force null checking to eliminate the possibility of forgetting null checking" is correct ... So the sample code works, but it is not a code written with correct recognition as to how to use Optional. I will leave this article without deleting it so that I will not forget it, but please be careful not to get caught by someone like me who is "Optional for the first time!" Thank you, @sikani! After all, you have to have an expert review it ... Fortunately, I was unhappy that I didn't mention writing in Optional in other people's reviews. (Because it is a matter that Java8-like code is not forced)

Sample code

Java 1.6 is intentionally written in a strange way. Java 8 can be written neatly: relaxed: For Java8 ** It's a little wrong to use. ** ~~ Even with Java 1.6, you can write with a one-liner with a ternary operator, but ... ret is just useless, if ~ else is used without even early return, and the private method is not cut, and if is written every time. Most of the legacy code isn't really cool, so refactoring always kills me. Furthermore, even if I use Java 8, there are too many members who write Java 1.6 as it is, and I laugh anymore. I'm in trouble because I'm likely to misunderstand myself as a highly conscious system ... I remember the recent controversy over the upper ranks. ~~ I'm sorry to complain.

Java1.6


public String toStringIfNotNull(final Object obj) {
	String ret;
	if (obj == null) {
		ret = null;
	} else {
		ret = obj.toString();
	}
	return ret;
}

Java8


public String toStringIfNotNull(final Object obj) {
	return Optional.ofNullable(obj).map(Object::toString).orElse(null);
}

If you use Optional instead of null check, the combination of ʻof Nullable and ʻor Else may be the best solution than ʻof! ?? Impression. If it is not null and the original value is returned as it is, is it map` or intermediate processing? Is just unnecessary.

Besides map, there are filter and flatMap. filter returns the argument of ʻorElseif it is null and the filter result is false. IfflatMap is null, the argument of ʻorElse is returned, but if the result of flatMap processing is null, a NullPointerException is thrown. (In the case of map, the argument of ʻor Else` is returned even if the processing result is null)

If you want to branch the process instead of returning the value depending on whether it is null or not, you can write ʻif (Optional.ofNullable (obj) .isPresent ()). Also, ʻisPresent only returns a boolean value, but if you set it to ʻifPresentand pass a lambda expression as an argument, you can write that the lambda expression of the argument is executed only when it is not null. Well, if it's Java 7 or later, I think it's better to branch with ʻif (Objects.isNull (obj))(nonNull) than isPresent.

I noticed that I wrote so far, but if it is the processing content of the sample code, ʻObjects.toString (obj, null) `(something like StringUtils.defaultString) was good ... I was not sure enough.

Recommended Posts

[Java] Optional memorandum
Java memorandum
JAVA memorandum
Java Optional type
Studying Java 8 (Optional)
Java study memorandum
Java 9 Optional :: stream
View Java Optional Javadoc
webApi memorandum in java
Java8 Silver exam memorandum
Java8 Gold exam memorandum
Rewrite Java try-catch with Optional
memorandum
[Java] How to use Optional ②
Java
Java 3 major elements (object-oriented) memorandum
Java8 to start now ~ Optional ~
memorandum
Java
[Java] How to use Optional ①
Compare Java 8 Optional with Swift
Basic usage of java Optional Part 1
Java learning (0)
Studying Java ―― 3
[Java] array
Conversion between Kotlin nullable and Java Optional
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java string
java (array)
Java serialization
java beginner 4
JAVA paid
Memorandum of new graduate SES [Java basics]
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
MyBatis memorandum
Studying Java -5
java reflexes
java (interface)
☾ Java / Collection
Java array
Studying Java ―― 1
[Creating] A memorandum about coding in Java
[Java] Polymorphism
Studying Java # 0
Java review