I have written a below routine in Java, I need to know that the code is Null Pointer Safe or not:
public class TRM_Fields {
public static String returnActualValue(String Staffing_Event,
String CurrentValue, String PriorValue) {
String returnValue;
returnValue = null;
if ("TRM".equalsIgnoreCase(Staffing_Event) && CurrentValue == null
&& PriorValue != null && !"".equalsIgnoreCase(PriorValue)) {
returnValue = PriorValue;
} else {
returnValue = CurrentValue;
}
return returnValue;
}
}
Any of the parameter Staffing_Event, CurrentValue and PriorValue may be null.
If it is not Null Pointer Safe what should I do to achieve that?
Your method is safe. You are correctly using "constantString".equals(someObject) to ensure a null-safe comparison.
Some other comments:
Your method is hard to read because you are using TitleCase for Java variables, when they should be camelCase.
You only have two possible return values. So you can simplify your method as follows:
public static String returnActualValue(String staffingEvent,
String currentValue, String priorValue) {
if ("TRM".equalsIgnoreCase(staffingEvent) && currentValue == null
&& priorValue != null && !"".equalsIgnoreCase(priorValue)) {
return priorValue;
} else {
return currentValue;
}
}
Note that the else construct isn't necessary, so it's a matter of style whether you include that structure or simply have return currentValue;.
Related
I have to ensure if two values are non null. When the first and second have non null values, pass first as argument to second. If one of them are null value, then return false.
This can be done in the following piece of code:
String value1 = function_to_get_value1()
if (value1 == null) return false;
String value2 = function_to_get_value2(value1)
if (value2 == null) return false;
return true;
It can also be done in short form:
try {
return function_to_get_value2(function_to_get_value1()) != null;
} catch (NullPointerException e) {
return false;
}
I was wondering how to do this in fluent form with Optional.
You could try something like this:
return Optional.ofNullable(function_to_get_value1())
.map(v1 -> function_to_get_value2(v1))
.isPresent();
map() applies the lambda if value is present and returns a new Optional.ofNullable() or otherwise returns an empty Optional. So in the end you have an empty Optional if either value was null or a non-empty one.
If you have a look at the source code for those methods, it basically is equivalent to this:
//Optional.ofNullable(...)
Optional<UiObject> v1Opt = value1 == null ? Optional.empty() : Optional.of(value1);
//Optional.map(...)
Optional<UiObject> v2Opt;
if(v1Opt.isPresent()) {
//this is the lambda
UiObject value2 = function_to_get_value2(value1);
//Optional.ofNullable(...) called in map(...)
v2Opt = value2 == null ? Optional.empty() : Optional.of(value2);
} else {
v2Opt = Optional.empty();
}
//Optional.isPresent()
return v2Opt.value != null;
I can't check whether a string is empty or not coming from rest service as input stream which then I am changing into string for parsing.
public boolean isNullorEmpty(String string)
{
if(string !=null || !string.isEmpty() || string.length()>0)
return true;
else
return false;
}
Please help me out to check if string is empty or not.
The current problem in your code is that if the string you pass in argument is null, thenstring !=null is evaluated to false. Hence you'll try to evaluate !string.isEmpty() which will lead to a NullPointerException.
On the other hand if you pass a String that is not null (ex "" or "test"), string != null is evaluated to true and hence you return true.
So to fix that you should, as the name of your method suggests, check if the String is null OR empty.
But since you're on android, don't reinvent the wheel and use TextUtils.isEmpty(CharSequence str).
boolean isEmpty = TextUtils.isEmpty(myString);
Returns true if the string is null or 0-length.
If you want to look about how is it implemented:
427 public static boolean isEmpty(CharSequence str) {
428 if (str == null || str.length() == 0)
429 return true;
430 else
431 return false;
432 }
Well, this can be handled in plain java like:
And it can be written like:
public boolean isStringEmpty (){
if(str ==null || str.isEmpty () || str.trim().equals("")){
return true;
}
return false;
}
I'm writing a method that should return the first item in an array belonging to a certain user. The class looks like this:
public MailItem getNextMailItem(String who)
{
return mailbox.get(who).pollFirst();
}
I need some sort of error handling in case the "who"-parameter is empty or null e.g
if (who != null && who.length() != 0)
But what if that turns out to be false?
your if block is something like that
public MailItem getNextMailItem(String who) {
MailItem item = null;
if (who != null && who.length() != 0) {
item = mailbox.get(who).pollFirst();
} else {
//show some error message or error log here
}
return item;
}
on filure your method will return null.
also read this Q&A
Returning null in the absence of a value would be an obvious solution:
public MailItem getNextMailItem(String who){
MailItem mailItem = null;
if (who != null && who.length() != 0){
mailItem = mailbox.get(who).pollFirst();
}
return mailItem;
}
But consider this:
If you communicate with null, your return value really is ambiguous. It can mean a lot of things. Instead, you could use Guava's Optional or the Null object pattern.
Using the Null pattern, you would define an instance that has a neutral behavior, possibly in your MailItem interface, and return it in case of the absence of a value:
public MailItem getNextMailItem(String who) {
MailItem mailItem = null;
if (who != null && who.length() != 0){
mailbox.get(who).pollFirst();
} else {
mailItem = MailItem.NULL_ITEM;
}
return mailItem;
}
This way - unless an unexpected exception happens - you can always be sure that getNextMailItem returns a valid instance of MailItem.
Simple solution is to return null. On the other side, check for null and handle accordingly.
My enum declaration:
public enum Note { A, A_SHARP, B, C, C_SHARP, D, D_SHARP,
E, F, F_SHARP, G, G_SHARP;
public String toString(Note note) {
if (note == Note.A)
return "A";
else if (note == Note.A_SHARP)
return "A#";
else if (note == Note.B)
return "B";
else if (note == Note.C)
return "C";
else if (note == Note.C_SHARP)
return "C#";
else if (note == Note.D)
return "D";
else if (note == Note.D_SHARP)
return "D#";
else if (note == Note.E)
return "E";
else if (note == Note.F)
return "F";
else if (note == Note.F_SHARP)
return "F#";
else if (note == Note.G)
return "G";
else if (note == Note.G_SHARP)
return "G#";
else
return "";
}
public Note getNext() {
int index = ordinal();
index++;
if (index > values().length)
return values()[0];
else
return values()[index];
}
}
Whenever I call either of these two methods, my app crashes. Here is where I call them:
public void ChangeSound(View v) {
note = note.getNext();
tvSounds.setText(note.toString(note));
}
ChangeSound() is an onClick method for a button. If I remove both lines in ChangeSound(), the code works as it should, but if either of the two lines are in there, the app crashes on the button click. Any ideas why? Thanks in advance!!
EDIT**
note is a variable of type Note
Thank you everyone! It was returning null (look at Jason C's answers (my comment)). All of this was helpful for me!
You should use >= since probably you're getting some OutOfBoundsException
if (index >= values().length)
return values()[0];
else
return values()[index];
}
Also instead of switch you could sth like that:
public enum Note { A("A"), A_SHARP("A#"), B("B");
private String s;
public Note (String s) {
this.s = s;
}
public String toString() {
return s;
}
Change this:
if (index > values().length)
to this:
if (index >= values().length)
It's unclear what you mean by "crashes", and you also do not show enough context (what is 'note'?) but the most likely cause based on the fact that you stated either of those two lines crash seems to be that 'note' is null. If 'note' is null then ChangeSound will throw a NullPointerException. You need to make sure that if ChangeSound is assuming 'note' is not null, that that is actually the case.
Also you should make toString(Note) a static method, and define a non-static toString() override. This will give Note.toString(Note) the ability to handle nulls correctly:
public static String toString (Note n) {
return n == null ? "" : n.toString();
}
Edit: As noted in other answers, you should use >= instead of > (even == would be sufficient), that is also a potential problem.
The issue has already been spotted by the other answers. Note however that you could simplify your code in two ways:
by associating the String representation of the notes with the enum constants directly
by using a modulus instead of your if/else in getNext
It could look like:
public enum Note { A("A"), A_SHARP("A#"), B("B"), C("C"), C_SHARP("C#"), D("D"),
D_SHARP("D#"), E("E"), F("F"), F_SHARP("F#"), G("G"), G_SHARP("G#");
private final String noteName;
Note(String noteName) {
this.noteName = noteName;
}
#Override
public String toString() {
return noteName;
}
public Note getNext() {
int nextIndex = (ordinal() + 1) % values().length;
return values()[nextIndex];
}
}
And in your main code:
note = note.getNext();
tvSounds.setText(note.toString());
I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. So please suggest me the best ways with code snippet :)
I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (i.e ValidateInputFiled )
Contents unmarshalledValues = unmarshalingContent( xml );
inputCheck = ValidateInputField( unmarshalledValues );
I have a POJO for my XML elements as mentioned below,
#XmlRootElement( name = "contents" )
public class Contents
{
#XmlElement
String A;
#XmlElement
String B;
#XmlElement
String C;
#XmlAttribute
String D;
public String getA()
{
return A;
}
public String getB()
{
return B;
}
public String getC()
{
return C;
}
public String getD()
{
return D;
}
}
I have defined ValidateInputFiled as mentioned below
public Boolean ValidateInputField( Contents unmarshalledValues )
{
int checker = 0;
Boolean listCheck = false;
// Extracting unmarshalled values from xml
String A= unmarshalledValues.getA();
String B= unmarshalledValues.getB();
String C = unmarshalledValues.getC();
String D= unmarshalledValues.getD();
if ( A== null || A.isEmpty() )
{
checker++;
}
if ( B== null || B.isEmpty() )
{
checker++;
}
if ( C== null || C.isEmpty() )
{
checker++;
}
if ( D== null || D.isEmpty() )
{
checker++;
}
if ( checker == 0 )
{
listCheck = true;
}
return listCheck;
}
Here i am looking to avoid NULL check for each String Values ( i.e A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ?
public static boolean isNullOrEmpty(String a) {
return a == null || a.isEmpty();
}
Call that for each value. You may want to think about adding them all to a list and then iterating through them, incrementing checker if they're !isNullOrEmpty to save code bloat if you have lots for fields.
PS: Make your fields private to preserve encapsulation.
pps: don't bother with a seperate boolean just return checker == 0; to keep the code neat.
Is that what you are looking for ?
public Boolean ValidateInputField(Contents unmarshalledValues) {
// Extracting unmarshalled values from xml
String A = unmarshalledValues.getA();
String B = unmarshalledValues.getB();
String C = unmarshalledValues.getC();
String D = unmarshalledValues.getD();
return checkNull(A, B, C, D);
}
private static boolean checkNull(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return false;
}
}
return true;
}
I use the apache commons StringUtils library for this type of thing. It has a check that includes null or empty spaces, plus other combinations depending on how you treat empty spaces. Pretty much code like Jeff here gave you, but i like having other methods they include.
You can also avoid nulls alltogether by coding your getters to return "" if a value == null. Then you would not have to check each field for null.
commons-lang has a Validate class you could use:
Validate.notNull( unmarshalledValues.getA() );
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name).allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.