Is there a better way to do an empty check in Java? [duplicate] The 2019 Stack Overflow...
Cooking pasta in a water boiler
Pokemon Turn Based battle (Python)
Keeping a retro style to sci-fi spaceships?
Why “相同意思的词” is called “同义词” instead of "同意词"?
How can I define good in a religion that claims no moral authority?
What is this sharp, curved notch on my knife for?
"as much details as you can remember"
A word that means fill it to the required quantity
The phrase "to the numbers born"?
Why doesn't UInt have a toDouble()?
What does Linus Torvalds mean when he says that Git "never ever" tracks a file?
Why isn't the circumferential light around the M87 black hole's event horizon symmetric?
APIPA and LAN Broadcast Domain
Are spiders unable to hurt humans, especially very small spiders?
How do you keep chess fun when your opponent constantly beats you?
Deal with toxic manager when you can't quit
Why couldn't they take pictures of a closer black hole?
How to display lines in a file like ls displays files in a directory?
Can I have a signal generator on while it's not connected?
Straighten subgroup lattice
How to support a colleague who finds meetings extremely tiring?
Button changing its text & action. Good or terrible?
Dropping list elements from nested list after evaluation
Are there any other methods to apply to solving simultaneous equations?
Is there a better way to do an empty check in Java? [duplicate]
The 2019 Stack Overflow Developer Survey Results Are InHow to check multiple objects for nullity?Check chains of “get” calls for nullHow better refactor chain of methods that can return null in java?Check if last getter in method chain is not nullTry-Catch Instead of Null Check When Using Several Getterstry/catch vs null check in javaTry Catch Performance JavaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?Fastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What's the simplest way to print a Java array?How do I convert a String to an int in Java?Creating a memory leak with Java
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
This question already has an answer here:
Check chains of “get” calls for null
8 answers
Check if last getter in method chain is not null
3 answers
How to check multiple objects for nullity?
5 answers
Try-Catch Instead of Null Check When Using Several Getters
3 answers
How better refactor chain of methods that can return null in java?
10 answers
This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.
The goal is to check the value of a boolean field that is nested under two objects.
private boolean sourceWebsite(Registration registration) {
Application application = registration.getApplication();
if (application == null) {
return true;
}
Metadata metadata = application.getMetadata();
if (metadata == null) {
return true;
}
Boolean source = metadata.getSource();
if (source == null) {
return true;
}
return !source;
}
I know this could be done in a single if()
. I have added multiple if
s here for the sake of readability.
Is there a way that we could simplify the above if
statements and have a simple utility class that returns the value of Boolean source
if the parent objects or not null?
java if-statement conditional
marked as duplicate by Sotirios Delimanolis
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
10 hours ago
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
This question already has an answer here:
Check chains of “get” calls for null
8 answers
Check if last getter in method chain is not null
3 answers
How to check multiple objects for nullity?
5 answers
Try-Catch Instead of Null Check When Using Several Getters
3 answers
How better refactor chain of methods that can return null in java?
10 answers
This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.
The goal is to check the value of a boolean field that is nested under two objects.
private boolean sourceWebsite(Registration registration) {
Application application = registration.getApplication();
if (application == null) {
return true;
}
Metadata metadata = application.getMetadata();
if (metadata == null) {
return true;
}
Boolean source = metadata.getSource();
if (source == null) {
return true;
}
return !source;
}
I know this could be done in a single if()
. I have added multiple if
s here for the sake of readability.
Is there a way that we could simplify the above if
statements and have a simple utility class that returns the value of Boolean source
if the parent objects or not null?
java if-statement conditional
marked as duplicate by Sotirios Delimanolis
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
10 hours ago
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
This question already has an answer here:
Check chains of “get” calls for null
8 answers
Check if last getter in method chain is not null
3 answers
How to check multiple objects for nullity?
5 answers
Try-Catch Instead of Null Check When Using Several Getters
3 answers
How better refactor chain of methods that can return null in java?
10 answers
This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.
The goal is to check the value of a boolean field that is nested under two objects.
private boolean sourceWebsite(Registration registration) {
Application application = registration.getApplication();
if (application == null) {
return true;
}
Metadata metadata = application.getMetadata();
if (metadata == null) {
return true;
}
Boolean source = metadata.getSource();
if (source == null) {
return true;
}
return !source;
}
I know this could be done in a single if()
. I have added multiple if
s here for the sake of readability.
Is there a way that we could simplify the above if
statements and have a simple utility class that returns the value of Boolean source
if the parent objects or not null?
java if-statement conditional
This question already has an answer here:
Check chains of “get” calls for null
8 answers
Check if last getter in method chain is not null
3 answers
How to check multiple objects for nullity?
5 answers
Try-Catch Instead of Null Check When Using Several Getters
3 answers
How better refactor chain of methods that can return null in java?
10 answers
This might look like a primitive question or a this could be done by a simple utility library method that I don't know about.
The goal is to check the value of a boolean field that is nested under two objects.
private boolean sourceWebsite(Registration registration) {
Application application = registration.getApplication();
if (application == null) {
return true;
}
Metadata metadata = application.getMetadata();
if (metadata == null) {
return true;
}
Boolean source = metadata.getSource();
if (source == null) {
return true;
}
return !source;
}
I know this could be done in a single if()
. I have added multiple if
s here for the sake of readability.
Is there a way that we could simplify the above if
statements and have a simple utility class that returns the value of Boolean source
if the parent objects or not null?
This question already has an answer here:
Check chains of “get” calls for null
8 answers
Check if last getter in method chain is not null
3 answers
How to check multiple objects for nullity?
5 answers
Try-Catch Instead of Null Check When Using Several Getters
3 answers
How better refactor chain of methods that can return null in java?
10 answers
java if-statement conditional
java if-statement conditional
edited 14 hours ago
Peter Mortensen
13.9k1987113
13.9k1987113
asked 16 hours ago
codeMancodeMan
4,44721646
4,44721646
marked as duplicate by Sotirios Delimanolis
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
10 hours ago
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Sotirios Delimanolis
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
10 hours ago
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
9
Boolean.FALSE::equals
instead ofsource -> !source
if you really love method reference
– Adrian
15 hours ago
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
Return type isboolean
so.orElse(true);
would be better.
– user11153
14 hours ago
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
|
show 4 more comments
The following will return true if any one of is null. If all values are not null, it returns !source
.
private boolean sourceWebsite(Registration registration) {
return registration.getApplication() == null
|| registration.getApplication().getMetadata() == null
|| registration.getApplication().getMetadata().getSource() == null
|| !registration.getApplication().getMetadata().getSource();
}
Updated :
If you want that every getter not called more than once then you can declare variable for every object like
private boolean sourceWebsite(Registration registration) {
Application application;
Metadata metadata;
Source source;
return (application = registration.getApplication()) == null
|| (metadata = application.getMetadata()) == null
|| (source = metadata.getSource()) == null
|| !source;
}
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
|
show 8 more comments
Another option you can use is a try-catch block. If you get a null pointer exception return true.
private boolean sourceWebsite(Registration registration) {
try {
return !registration.getApplication().getMetadata().getSource();
}
catch (NullPointerException e) {
return true;
}
}
New contributor
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
|
show 2 more comments
You could do it using a hacky method like this:
public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (o == null || m.length == 0) {
return null;
}
for (String m1 : m) {
o = o.getClass().getMethod(m1).invoke(o);
if (o == null) {
return null;
}
}
return o;
}
And call it like this:
Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;
But I wouldn't do it this way in any serious projects.
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit likereturn Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well useOptional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.
– Eric Duminil
10 hours ago
add a comment |
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
9
Boolean.FALSE::equals
instead ofsource -> !source
if you really love method reference
– Adrian
15 hours ago
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
Return type isboolean
so.orElse(true);
would be better.
– user11153
14 hours ago
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
|
show 4 more comments
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
9
Boolean.FALSE::equals
instead ofsource -> !source
if you really love method reference
– Adrian
15 hours ago
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
Return type isboolean
so.orElse(true);
would be better.
– user11153
14 hours ago
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
|
show 4 more comments
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
You can use java.util.Optional
in this way:
private boolean sourceWebsite(Registration registration) {
return Optional.of(registration)
.map(Registration::getApplication)
.map(Application::getMetadata)
.map(Metadata::getSource)
.map(source -> !source)
.orElse(Boolean.TRUE);
}
In short, this will return true
if any of the getters returns null, and !Metadata.source
otherwise.
edited 11 hours ago
Captain Man
3,29932855
3,29932855
answered 16 hours ago
ernest_kernest_k
24.8k43151
24.8k43151
9
Boolean.FALSE::equals
instead ofsource -> !source
if you really love method reference
– Adrian
15 hours ago
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
Return type isboolean
so.orElse(true);
would be better.
– user11153
14 hours ago
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
|
show 4 more comments
9
Boolean.FALSE::equals
instead ofsource -> !source
if you really love method reference
– Adrian
15 hours ago
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
Return type isboolean
so.orElse(true);
would be better.
– user11153
14 hours ago
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
9
9
Boolean.FALSE::equals
instead of source -> !source
if you really love method reference– Adrian
15 hours ago
Boolean.FALSE::equals
instead of source -> !source
if you really love method reference– Adrian
15 hours ago
2
2
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
I think you meant ` Optional.ofNullable()`
– dehasi
14 hours ago
1
1
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
Sorry, you are right. I've upvoted :)
– dehasi
14 hours ago
1
1
Return type is
boolean
so .orElse(true);
would be better.– user11153
14 hours ago
Return type is
boolean
so .orElse(true);
would be better.– user11153
14 hours ago
2
2
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
@user11153 The parameter requires a Boolean.. you give it a boolean and so it has to be boxed. It's not one unboxing less but one boxing more
– ave4496
12 hours ago
|
show 4 more comments
The following will return true if any one of is null. If all values are not null, it returns !source
.
private boolean sourceWebsite(Registration registration) {
return registration.getApplication() == null
|| registration.getApplication().getMetadata() == null
|| registration.getApplication().getMetadata().getSource() == null
|| !registration.getApplication().getMetadata().getSource();
}
Updated :
If you want that every getter not called more than once then you can declare variable for every object like
private boolean sourceWebsite(Registration registration) {
Application application;
Metadata metadata;
Source source;
return (application = registration.getApplication()) == null
|| (metadata = application.getMetadata()) == null
|| (source = metadata.getSource()) == null
|| !source;
}
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
|
show 8 more comments
The following will return true if any one of is null. If all values are not null, it returns !source
.
private boolean sourceWebsite(Registration registration) {
return registration.getApplication() == null
|| registration.getApplication().getMetadata() == null
|| registration.getApplication().getMetadata().getSource() == null
|| !registration.getApplication().getMetadata().getSource();
}
Updated :
If you want that every getter not called more than once then you can declare variable for every object like
private boolean sourceWebsite(Registration registration) {
Application application;
Metadata metadata;
Source source;
return (application = registration.getApplication()) == null
|| (metadata = application.getMetadata()) == null
|| (source = metadata.getSource()) == null
|| !source;
}
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
|
show 8 more comments
The following will return true if any one of is null. If all values are not null, it returns !source
.
private boolean sourceWebsite(Registration registration) {
return registration.getApplication() == null
|| registration.getApplication().getMetadata() == null
|| registration.getApplication().getMetadata().getSource() == null
|| !registration.getApplication().getMetadata().getSource();
}
Updated :
If you want that every getter not called more than once then you can declare variable for every object like
private boolean sourceWebsite(Registration registration) {
Application application;
Metadata metadata;
Source source;
return (application = registration.getApplication()) == null
|| (metadata = application.getMetadata()) == null
|| (source = metadata.getSource()) == null
|| !source;
}
The following will return true if any one of is null. If all values are not null, it returns !source
.
private boolean sourceWebsite(Registration registration) {
return registration.getApplication() == null
|| registration.getApplication().getMetadata() == null
|| registration.getApplication().getMetadata().getSource() == null
|| !registration.getApplication().getMetadata().getSource();
}
Updated :
If you want that every getter not called more than once then you can declare variable for every object like
private boolean sourceWebsite(Registration registration) {
Application application;
Metadata metadata;
Source source;
return (application = registration.getApplication()) == null
|| (metadata = application.getMetadata()) == null
|| (source = metadata.getSource()) == null
|| !source;
}
edited 11 hours ago
answered 16 hours ago
Khalid ShahKhalid Shah
2,23621025
2,23621025
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
|
show 8 more comments
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
5
5
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
The null-conditional operator (?.) of c# is for shure a nice thing...
– keuleJ
16 hours ago
3
3
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
One problem I see is with that pattern is that it executes getApplication 4 times, getMetadata 3 times and getSource 2 times. If they are all trivial getters, this might not be that much of a problem. But if their implementation is non-trivial (or even worse: not side-effect free) this might become a problem.
– Philipp
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
@Philipp yes. But in general getters are trivial.
– Khalid Shah
15 hours ago
5
5
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
In general they should be side-effect free, but that assumes that you are working with classes written by people who knew what they were doing and followed good software engineering principles and Java best practices. In the real world, that's a very brave assumption.
– Philipp
15 hours ago
1
1
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
@EricDuminil You generally can not rely on that. The JVM might be able to optimize these method calls away when they are trivial getters, but it might not be able to do that when they have some logic and it certainly won't be able to do it when they have side-effects.
– Philipp
11 hours ago
|
show 8 more comments
Another option you can use is a try-catch block. If you get a null pointer exception return true.
private boolean sourceWebsite(Registration registration) {
try {
return !registration.getApplication().getMetadata().getSource();
}
catch (NullPointerException e) {
return true;
}
}
New contributor
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
|
show 2 more comments
Another option you can use is a try-catch block. If you get a null pointer exception return true.
private boolean sourceWebsite(Registration registration) {
try {
return !registration.getApplication().getMetadata().getSource();
}
catch (NullPointerException e) {
return true;
}
}
New contributor
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
|
show 2 more comments
Another option you can use is a try-catch block. If you get a null pointer exception return true.
private boolean sourceWebsite(Registration registration) {
try {
return !registration.getApplication().getMetadata().getSource();
}
catch (NullPointerException e) {
return true;
}
}
New contributor
Another option you can use is a try-catch block. If you get a null pointer exception return true.
private boolean sourceWebsite(Registration registration) {
try {
return !registration.getApplication().getMetadata().getSource();
}
catch (NullPointerException e) {
return true;
}
}
New contributor
edited 12 hours ago
New contributor
answered 13 hours ago
CaptianObviousCaptianObvious
5713
5713
New contributor
New contributor
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
|
show 2 more comments
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
6
6
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
You shouldn't use exceptions for program logic. Exceptions should be used in case of an unrecoverable state in a program where it's better to stop the entire flow rather than try and recover.
– Nzall
13 hours ago
1
1
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
In general I do agree with you (doing so might make the code harder to follow if it wasn't this short), and I feel that using Optional is correct choice here (assuming you are using a new enough version of java to have access to it). The question asked for a way to handle these checks without several null checks. This will do that.
– CaptianObvious
13 hours ago
1
1
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
@Nzall Exceptions can also be useful in program logic, for instance as a very readable way of checking if a string parses into a number which is very similar to CaptainObvious answer.
– Old Nick
12 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Backing up the comment from Nzall: stackoverflow.com/a/8255933/6296561 - TL;DR: exceptions are heavy
– Zoe
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
Until a NPE is thrown much deeper in one of those methods.
– Koekje
11 hours ago
|
show 2 more comments
You could do it using a hacky method like this:
public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (o == null || m.length == 0) {
return null;
}
for (String m1 : m) {
o = o.getClass().getMethod(m1).invoke(o);
if (o == null) {
return null;
}
}
return o;
}
And call it like this:
Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;
But I wouldn't do it this way in any serious projects.
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit likereturn Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well useOptional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.
– Eric Duminil
10 hours ago
add a comment |
You could do it using a hacky method like this:
public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (o == null || m.length == 0) {
return null;
}
for (String m1 : m) {
o = o.getClass().getMethod(m1).invoke(o);
if (o == null) {
return null;
}
}
return o;
}
And call it like this:
Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;
But I wouldn't do it this way in any serious projects.
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit likereturn Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well useOptional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.
– Eric Duminil
10 hours ago
add a comment |
You could do it using a hacky method like this:
public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (o == null || m.length == 0) {
return null;
}
for (String m1 : m) {
o = o.getClass().getMethod(m1).invoke(o);
if (o == null) {
return null;
}
}
return o;
}
And call it like this:
Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;
But I wouldn't do it this way in any serious projects.
You could do it using a hacky method like this:
public static Object get(Object o, String... m) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (o == null || m.length == 0) {
return null;
}
for (String m1 : m) {
o = o.getClass().getMethod(m1).invoke(o);
if (o == null) {
return null;
}
}
return o;
}
And call it like this:
Boolean source = (Boolean) get(registration, "getApplication", "getMetadata", "getSource");
return source == null ? false : !source;
But I wouldn't do it this way in any serious projects.
edited 13 hours ago
answered 14 hours ago
Mika LammiMika Lammi
975619
975619
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit likereturn Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well useOptional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.
– Eric Duminil
10 hours ago
add a comment |
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit likereturn Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well useOptional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.
– Eric Duminil
10 hours ago
2
2
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
This is bad code in so many aspects: slow, not controlled by the compiler, immune to refactoring aids from the IDE. Even you recognize that you wouldn't use this in any serious projects. But then: what's the point? No one would bother to post a question or even read the answers for unserious projects.
– julodnik
12 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like
return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well use Optional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.– Eric Duminil
10 hours ago
It could become a bit better if you passed Methods as parameters instead of strings. It would probably look a bit like
return Optional.of(registration).map(Registration::getApplication).map(Application::getMetadata).map(Metadata::getSource)
so you might as well use Optional
directly. Still, I don't think you deserved downvotes. This method is still interesting as a thought experiment.– Eric Duminil
10 hours ago
add a comment |