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 8 years ago.
Improve this question
we have a dicussion about that method -
public static AbstractAttribute getAttribute(List<AbstractAttribute> attributes, String name) {
if ((attributes != null) && (name != null) && !name.trim().isEmpty()) {
for (AbstractAttribute attribute : attributes) {
if (attribute.getName().equalsIgnoreCase(name)) {
return attribute;
}
}
}
return null;
}
Is that priori right or not?
IMO there must be checking arguments logic with some exceptions to prevent the "client" wrong using.
So that u must review your code that uses this method in case of error instead of thinking that everything is ok and "list = null" returns the "null" as it does not contain some given key even if list is null though
===========Updated====
there exist 4 general cases for calling that method -
getAttribute(null,null); // returns null
getAttribute(list,null); // returns null
getAttribute(null,name); // returns null
getAttribute(list,name); // may return null if not found
all of them may return null, so how client can understand the difference between different type of calls? He might have made mistake calling method with null argument - and he recieved the null result as if everything ok and attribute just not found in list, but it CANT be found at all.
Hmm... don't know, but i think there must be arg checking...
What you should ask yourself is, which is more useful to a developer?
AbstractAttribute a = getAttribute(null, "name");
a.something(); // Oh no, null pointer.
or
AbstractAttribute a = getAttribute(null, "name"); // Oh no, invalid argument exception.
Your Exception should ALWAYS be as close to the actual problem as possible. If they have a problem with their arguments that fatally interrupts the functionality of the method, then throw an exception! The developer needs to know their mistake and the duty falls to you to make sure it's as clear as possible.
Edit
Yes, you're on the right lines. Your message needs to be specific.
public Object myFunction(String something, String somethingElse) {
// First option - Not so good.
if(something == null || somethingElse == null) {
throw new IllegalArgumentException("Invalid parameters. Can not be null");
}
// Second option - much better.
if(something == null) {
throw new IllegalArgumentException("Something can not be null");
}
if(somethingElse == null) {
throw new IllegalArgumentException("Something else can not be null");
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have one field called isExist and it is either false or true in line #1.
based on this, in line#2 either Optional.empty() is executed or Optional.of(1) is getting executed but never Exception is thrown from orElseThrow method in line#2.
can anyone please explain when Exception will be thrown ? on which condition Exception will be thrown ?
line#1 final boolean isExist = (user != null && CollectionUtils.isNotEmpty(user.getIds())
&& user.getIds().contains(id));
line#2 (isExist ? Optional.empty() : Optional.of(1)).orElseThrow(
() -> new Exception());
From line1, it will assign true/false to isExist variable.
So we have 2 possibility here.
isExist = true or isExist = false;
At line 2, the tertiary condition can be understand as:
Optional optional = null;
if(isExist){
optional = Optional.empty();
}else{
optional = Optional.of(1)
}
optional.orElseThrow(() -> new Exception());
orElseThrow only throw exception when optional variable is empty, it mean when isExist = true. If isExist = false, nothing happen.
You can see below signature to understand the basic concept of orElseThrow ...
public void orElseThrow(Exception ex){
if(!isPresent()){
throw ex;
}
}
Don't use Optional for this. It's just not necessary. Use plain imperative code:
if (!isExist) {
throw new Exception();
}
// You don't show what you do with the result, but presumably you do something
// like return or assign to a variable:
return 1;
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 3 years ago.
Improve this question
I've heard that it is bad practice to return null.
What are the alternatives to returning null in this case?
public RollingStock getHeadPoint() {
if (!train.isEmpty()) {
return train.get(0);
} else {
return null;
}
}
IMHO, the best option is to return an Optional<RollingStock>, like the foillowing:
public Optional<RollingStock> getHeadPoint() {
if (!train.isEmpty()) {
// or even Optional.ofNullable, if you are not sure
// whether train.get(0) is null or not
return Optional.of(train.get(0));
} else {
return Optional.empty();
}
}
Assuming train is a collection, as an alternative to manual wrapping the value into an Optional you could use Stream API:
public Optional<RollingStock> getHeadPoint() {
return train.stream()
.findFirst();
}
In some cases using inline train.stream().findFirst() may be more preferable than wrapping it into a separate method.
Once you already modified your method getHeadPoint to return Optional<RollingStock> you can use it as follows:
// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));
You could define a TrainIsEmptyException and throw that when the train is empty. Make it a checked Exception. Or you can just return null.
You should differentiate "get" and "search/find" methods :
getHeadPoint : some train should exist. If not, it's against your business, throw an exception
findHeadPoint : non-existence of the train is coherent to your business, return null
This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
Handle Chained Method Calls avoiding NullPointerException - Which is the best way?
Let's imagine this kind of scenario:
3 class Meeting, Room, Projector
A Meeting might have set a Room and it might have a Projector inside them.
Now suppose that I want to know what is the model of the Projector.
The most natural thing is to do something like
Meeting meeting = someMethod();
return meeting.getRoom().getProjector().getModelName();
This code could return the model name of the Projector correctly,
unfortunately this code could also cause an Exeption: an java.lang.NullPointerException in case that one of the class contained into the root class Meeting (or even the Meeting class) is null.
In order to prevent this problem, and get a default value in the worst case we should check the returned value of each call.
Meeting meeting = someMethod();
if (meeting != null) {
Room room = meeting.getRoom();
if (room != null) {
Projector projector = room.getProjector();
if (projector != null) {
return projector.getModelName;
}
}
}
return "No Projector Exist";
The code now is pretty nasty.
What is the best way to deal with this kind of chained method calls avoiding the NullPointerException?
Use Optional:
return Optional.ofNullable(someMethod())
.map(Meeting::getRoom)
.map(Room::getProjector)
.map(Projector::getModelName)
.orElse("No Projector Exist");
As an aside, consider returning Optional or null from your method - having to compare your String to the special hardcoded value to detect the null case is going to get tiresome...
Checking all the null conditions in one if statement also can be done as follows.
So that the code will be much easier to read.
if (meeting != null && meeting.getRoom() != null && meeting.getRoom().getProjector() != null) {
return meeting.getRoom().getProjector().getModelName();
} else {
return "No Projector Exist";
}
The best way is to move the null checks to a private method. So when you give a meeting object, it do the required checks and return the model of the project as a string. So your code will be much simpler and with less complex.
You can catch() the NullPointerException or throw a NoRoomException and a NoProjectorException from your getRoom() and getProjector() methods and catch those.
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 5 years ago.
Improve this question
I have this piece of code:
Name name = address.getName();
if (null != name && null != name.getFullName()) {
addressInfo.setName(name.getFullName());
} else {
addressInfo.setName(StringUtils.EMPTY);
}
Email emailProfile = address.getEmailAddresses();
if (null != emailProfile && emailProfile.hasPrimaryEmail()) {
addressInfo.setEmail(emailProfile.getPrimaryEmail().getEmailAddress());
} else {
addressInfo.setEmail(StringUtils.EMPTY);
}
VoicePhone voicePhoneProfile = address.getVoicePhones();
if (null != voicePhoneProfile && voicePhoneProfile.hasPrimaryPhone()) {
addressInfo.setPhoneNumber(voicePhoneProfile.getPrimaryPhone().getPhoneNumber());
} else {
addressInfo.setPhoneNumber(StringUtils.EMPTY);
}
They are basically doing the same thing but the getter and setter behavior is different.
Is there a way to write one single generic method to make these 3 block of code into 3 lines of code?
I would discourage trying to meld these methods together. There's a simpler win that you can get here, actually.
Take a closer look at what they're doing:
setName only sets the name to the full name if it exists, otherwise it defaults to "empty".
setEmail only sets the email address if it exists, otherwise it defaults to "empty".
setPhoneNumber only sets the phone number if a primary phone number exists, otherwise it defaults to "empty".
Enforce the defaults in the bean itself as opposed to the conditional logic here.
public class Name {
private String name = StringUtils.EMPTY;
}
// and so forth for Email and VoicePhone
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 5 years ago.
Improve this question
In Java, Foo.class.getMethod("bar") declares a checked exception of type NoSuchMethodException (among others).
What is the purpose of this exception? Isn't returning null sufficient to indicate that it was not found? What information or utility does throwing an exception add? Aside from forcing the user to explicitly be aware that it's possible for it to not be found, this seems superfluous. Returning null when something doesn't exist is a common pattern in Java, and this seems to be a prime candidate for that. So what was the reasoning behind this?
It appears that the designers of Java APIs made a distinction between situations when it's OK to ask for something that is missing and situations when you are supposed to ask only for things that exist.
They decided that asking for a missing key in a Map is OK, because the content of a map is something your program controls at runtime. Therefore, designers of the class library decided that it is unreasonable to ask programmers to check if a value is present before calling Map.get, and decided to return null instead.
The list of methods in a class, however, remains static at all times during a particular run, so it becomes reasonable to ask programmers to call getMethod only for methods that do exist. There are two consequences to this approach:
You can request multiple methods without checking each one - if you have a list of methods that must exist, for example, in a plugin component, you can get their Method reflection objects without checking the return value of individual getMethod calls, and
When you do not know if a method exists, call getMethods() - You can still examine all methods without knowing their names by getting a full list from the Class object.
Here is a code example to illustrate the first point. Current API lets you write this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
try {
init = cl.getMethod("init");
start = cl.getMethod("start");
stop = cl.getMethod("stop");
} catch (NoSuchMethodException ex) {
throw new PluginException("Plugin is missing a required method", ex);
}
}
...
}
instead of this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
init = cl.getMethod("init");
if (init == null) {
throw new PluginException("Plugin is missing init method");
}
start = cl.getMethod("start");
if (start == null) {
throw new PluginException("Plugin is missing start method");
}
stop = cl.getMethod("stop");
if (stop == null) {
throw new PluginException("Plugin is missing stop method");
}
}
...
}