Java 8 Optional ifPresent() vs != null [duplicate] - java

This question already has answers here:
Optional vs. null. What is the purpose of Optional in Java 8? [duplicate]
(3 answers)
Closed 7 years ago.
I understand that Optionals ifPresent() call is meant to replace a null check. Pulling code examples from the Oracle documentation, it appears to be very useful in simple situations. For example:
Optional<Soundcard> soundcard = ...;
soundcard.ifPresent(System.out::println);
I just want to understand why this is considered better than a null check. Readability? Performance? It seems to me that this would cause a hit to project performance, as a new object must be introduced in order to hold the object we ultimately wish to obtain? In full, why is this soundcard.ifPresent()
considered better than this if(soundcard != null).

Optional is a way of replacing a nullable reference with a non-null value. An Optional may either contain a non-null reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."
And besides readability it forces you to think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case.
Source: Using and Avoiding null
And as referred before, have a look at this thoroughly answered post.

Related

Why use Optional.of method if a missing value is not permitted per business logic [duplicate]

This question already has answers here:
Uses for Optional
(14 answers)
Closed 1 year ago.
Instead of initialising optCar variable as below:
Optional<'Car'> optCar = Optional.of(car);
Why not initialise it simply as :
Car optCar = car;
When a business logic does not permit car to be null?
You totally can.
Optional is for situations where you would have a code
If(object == null) {…
Instead you use Optional and then you have cool access to stream like features and or/or else statements that make ur code so much nicer, for example:
return Optional.ofNullable(object).orElse(defaultObject);
Or another example
return Optional.ofNullable(object).map(Object::toString).orElseThrow();
This last code return string representation of ur object if that optional is present or else throws an exception. orElseThrow is most useful in situations where you actually are sure that object is always there so such situation will likely never arise and if it does u know where to look.
But like I said in the beginning if you don’t need these features u don’t need to use it
if you are sure that car can never be null then using Optional would be an overkill.
The presence of Optional is to provide for clarity that this particular instance can be null and the Optional needs to be unwrapped and explicitly checked for the absence (or presence) of a value.
Do not go by what I say, hear it from the expert:
Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
Excerpted from Brian Goetz's answer here.

Do I need to check the null for optional object itself before use ? - optionalObj == null [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
When we use the Java 8 Optional feature, do we need to check the optional object itself is null before we call isPresent() ? see the 2nd line in my code below.
Optional<entity> optionalEntity = myRepository.findById(dao.getId());
if (optionalEntity != null) { // is this check need?
if(optionalEntity.isPresent() {
MyEntity entityToUpdate = optionalEntity.get();
}
}
No, you don't have to.
In theory, Optional<>s can be null but shouldn't be as the empty value would make more sense.
Returning a null Optional<> value is just bad API design.
Spring JPA uses Optional instead of null, just like it should do so you can skip the additional null check.
Also, using Optional#ifPresent indicates that you are using Optional incorrectly. You may want to use the other methods of Optional instead.
If you need to execute something if the Optional has a value, you can use the method Optional#ifPresent:
someOptional.ifPresent(value->doSomething(value));
This might not seem like a big advantage but it works well with other methods like Optional#map:
someOptional.map(value->value.getSomething()).ifPresent(value->doSomething(value))
Optional#map transforms the object in the Optional using the passed lambda expression.
Optional#filter replaces tte object in the Optional with null (empty Optional) if the object doesn't match the passed condition.
Do I need to check the null for optional object itself before use?
No, either do not use an Optional<T>, or if you're using it, try not to get in a habit of checking optional instances against null, as this defeats the purpose of Optional<T>.
Remember, that:
Optional<T> was not designed with an intention to swap null checks. It's a wrapper/container for a possibly existing object, nothing more, nothing less; therefore, in a lot of cases, it is just a nice, beautified and a concise alternative of boilerplate null-checks, with an addition, that you can chain activities, in just a line, when object is present;
Optional<T> is not serializable.
Cay Horstmann nicely says, that:
The key to using Optional effectively is to use a method that either produces an alternative if the value is not present, or consumes the value only if it is present.
You can use ifPresent(Consumer<? super T> consumer) and if a value is present, you can chain some corresponding activity calls.
isPresent() can also be used, in some cases, and it returns boolean; you can then get() an instance, if it isPresent().
Additionally, you can find this useful.

Avoiding null check when accessing an object property in java [duplicate]

This question already has answers here:
Null check in Java 8 Elvis operator?
(2 answers)
Closed 5 years ago.
I have a situation where I need get the property of a Java object if the object exists or null.
Something like foo == null ? null : foo.bar
Is there an operator available in java to do the same?
No, there is no propagate null operator in Java, cf. C# for example, which does have one. (It was a proposal at some point in Java's evolution, but has not sadly yet been incorporated into the language: foo = foo?.bar would be an obvious notation.)
You need to write this out longhand, as you have done.

Difference between using variable first and using variable at the end when comparing object? [duplicate]

This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 6 years ago.
I have seen in many places that the constant value is used first and then the variable for example ("ram").equals(a) and in many places I have seen that the variable is used first and then the constant value with which they want to compare for example a.equals("ram").
what is the difference between a.equals("ram") and ("ram").equals(a) ?
which one is better to use and why ?
The first style is safer in situations when variable a is allowed to be null, because you can skip null checking.
When you write
if (a.equals("ram")) { ... }
you must ensure that a is not null to avoid a null pointer exception. This is not necessary for
if ("ram".equals(a)) { ... }
because equals() method is required to process null arguments without throwing an exception:
For any non-null reference value x, x.equals(null) should return false.
("ram").equals(a) is better. The code will never break even if a is null.
saves us from null pointer exception.

why use null != anything instead of anything!=null? [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 7 years ago.
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too
"true".equals(x).
Why is this so?
anything != null is exactly equivalent to null != anything.
On the other hand, "true".equals(x) avoids the need to check if x is null when doing x.equals("true").
The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException even when the variable is null. This also improves the readability of the expression.
That being said, null!=something is a personal choice and I would prefer using something!=null.
These are two separate practices.
Using null on the left side when comparing to null ensures that you won't, by mistake, use = instead of ==. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException. It should be noted that this practice is controversial, because it allows a null to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.
This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing = or !, as in foo = null. The reverse, null = foo, would not even compile.
That said, it is purely a stylistic preference. foo != null is logically equivalent to null != foo.
That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as #manouti explains above, "true".equals(x) avoids the need to check if x is null when doing x.equals("true"), so you save a line of code.
Seems that some people prefer null != anything, because anything might be quite long expression, so writing null first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x), it's well explained by #manouti.

Categories

Resources