Introduce a new variable instead of reusing the parameter "entity" - java

I am solving SonarQube issues , in that issues I face an below warning any one please tell me how can i fix it,
Here is my class
public static Agency updateEntity(AgencyModel model, Agency entity) {
if (model == null || entity == null) {
return null;
}
if (entity.getAgencyId() != model.getAgencyId()) {
entity = new Agency()
// for the above variable 'entity' i get the warning, "Introduce a new
variable instead of reusing the parameter "entity".
}
entity.setAgencyId(model.getAgencyId());
if (entity.getAgencyLogoLarge() == null) {
entity.setAgencyLogoLarge(new File());
}
entity.setAgencyLogoLarge(FileModel.updateEntity(model.getAgencyLogoLarge(), entity.getAgencyLogoLarge()));
if (entity.getAgencyLogoSmall() == null) {
entity.setAgencyLogoSmall(new File());
}
entity.setAgencyLogoSmall(FileModel.updateEntity(model.getAgencyLogoSmall(), entity.getAgencyLogoSmall()));
entity.setAgencyName(model.getAgencyName());
entity.setContactPersons(
AgencyContactPersonModel.updateEntities(model.getContactPersons(), entity.getContactPersons()));
entity.setOtherDetails(model.getOtherDetails());
entity.setClassification(ClassificationModel.updateEntity(model.getClassification(), entity.getClassification()));
entity.setStatus(entity.getStatus());
entity.setCreatedBy((model.getCreatedBy() != null && model.getCreatedBy() != 0) ? model.getCreatedBy()
: entity.getCreatedBy());
entity.setUpdatedBy((model.getUpdatedBy() != null && model.getUpdatedBy() != 0) ? model.getUpdatedBy()
: entity.getUpdatedBy());
entity.setUpdatedDate(new Date());
entity.setStatus(Constant.ACTIVE);
return entity;
}
In above method i get that warning , will any one please tell me that what is the best approach to solve the above problem.

Assigning a value to a method argument often indicates a bug (even though this is not the case in your example), which is probably why SonarQube gives that warning.
Assuming you have no way of disabling that warning (or you don't want to), you can eliminate it by introducing a new local variable:
public static Agency updateEntity(AgencyModel model, Agency entity) {
Entity result;
if (model == null || entity == null) {
return null;
}
if (entity.getAgencyId() != model.getAgencyId()) {
result = new Agency();
} else {
result = entity;
}
... use result variable instead of entity variable ...
return result;
}

Related

Setting Default Value Strategy with Multiple Source Object in MapStruct

I want to generate null checks on mapped properties of my source objects and set to a default value if indeed the source property is null.
I have tried to use NullValuePropertyMappingStrategy.SET_TO_DEFAULT on #Mapper as well as on #Mapping targets but the generated code did not include the default setters..
So basically what I am trying to achieve is:
#Mapper(componentModel = "spring")
public interface OperationDataMapper {
OperationDTO from(Object 1 o1, Object2 o2);
}
So that my generated code becomes:
#Component
public class OperationDataMapperImpl implements OperationDataMapper {
#Override
public OperationDTO from(Object 1 o1, Object2 o2) {
if ( o1 == null && o2 == null ) {
return null;
}
OperationDTO operationDTO = new OperationDTO();
if ( o1 != null ) {
if(o1.getProp1() != null) {
operationDTO.setProp1( o1.getProp1() )
} else {
operationDTO.setProp1( "" ) // if property is a string for example
}
.
.
}
if ( o2 != null ) {
if(o2.getProp2() != null) {
operationDTO.setProp2( o2.getProp2() )
} else {
operationDTO.setProp2( "" ) // if property is a string for example
}
.
.
}
return operationDTO;
}
}
I didn't write my example with the default value strategy like the documentation points out because I it did not work on my attempts to map the nested properties with null values.. Interesting enough, the NullValueCheckStrategy works without any problems but the NullValuePropertyMappingStrategy does not.
I have also tried setting them using a #BeanMapping with no avail.
If someone could please point me in the right direction I would appreciate it!
The NullValuePropertyMappingStrategy is meant to be used for update mappings. If you want that to be applied you'll have to provide the OperationDTO through #MappingTarget.
The only way to achieve what you are looking for is to use Mapping#defaultValue or Mapping#defaultExpression

Findbugs-NP - NP_NULL_ON_SOME_PATH

Findbugs is showing NP_NULL_ON_SOME_PATH for a line.
It says that there is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed.
Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
Here is the code:
public int compare(Object o1, Object o2)
{
....
String sTypeName1 = row1.getFieldValue(OBJECT_TYPE_FIELD_NAME);
String sTypeName2 = row2.getFieldValue(OBJECT_TYPE_FIELD_NAME);
if (sTypeName1!= null && sTypeName1.indexOf("~") != -1)
{
sTypeName1 = m_oc.getString(sTypeName1);
}
if (sTypeName2!= null && sTypeName2.indexOf("~") != -1)
{
sTypeName2 = m_oc.getString(sTypeName2);
}
int cf = sTypeName1.compareTo(sTypeName2);
if (cf == 0)
{
cf = o1.toString().compareTo(o2.toString());
}
return cf;
}
It is showing 2 errors of same kind for the code:
int cf = sTypeName1.compareTo(sTypeName2);
Here it says that there is a possible null pointer dereference from the value loaded from sTypeName1.
So I had to put a null check before this code like:
if(sTypeName1 != null && sTypeName2 != null)
{
int cf = sTypeName1.compareTo(sTypeName2);
}
but the issue is not resolved. :(
Could anyone suggest a solution and also what is wrong with my approach?
Thanks a lot for going through my question :)
For me the issue is resolved. This code does not produce a bug report:
String sTypeName1 = row1.getFieldValue("qqq");
String sTypeName2 = row2.getFieldValue("www");
if (sTypeName1 != null && sTypeName1.indexOf("~") != -1) {
sTypeName1 = m_oc.getString(sTypeName1);
}
if (sTypeName2 != null && sTypeName2.indexOf("~") != -1) {
sTypeName2 = m_oc.getString(sTypeName2);
}
int cf = 0;
if (sTypeName1 != null && sTypeName2 != null) {
cf = sTypeName1.compareTo(sTypeName2);
}
if (cf == 0) {
cf = o1.toString().compareTo(o2.toString());
}
return cf;
Probably you did not recompile your code or did not perform the FindBugs analysis again.
From my experience this can be caused by situations like this:
Situation 1 - Findbugs will complain if you only set b under some conditions, such as if a is not null, then later reference b. If a could really be null, you need to handle what to do if b is null too as a result. If a is never null, remove the null check. Also, for me it identified the line where b was defined as the first problematic line, rather than when b.doSomething() is called.
if (a != null) {
b = a.getB();
}
b.doSomething();
Situation 2 - You nullcheck in one place, but not another. Nullcheck everywhere, or nowhere
if (x != null) {
x.doSomething1();
}
x.doSomething2();

How to handle a method where the parameter is tightly connected to the return value. What if the parameter is null? Java

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.

handling Null for bigdecimal

My code looks like below,
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null){
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
I have handled NUll pointer for the caseX and also for getter and when null set the bigdeciaml to a default ZERO value. Still I get Null pointer exception in the setter line.Any suggestions?
It's quite possible that caseXObj is null, so it'll cause the NullPointerException. You should test the three cases like this:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if (caseXObj != null && caseXObj.getCaseInGrossAmt() != null) {
// do something with caseXObj
} else if (caseXObj == null) {
// initialize caseXObj, you were misssing this case!
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
In essence, the error was that you were testing for only two cases - and there are three of them.
Assuming it is OK for getCaseXDao() to return null, you need to assign to caseXObj rather than use it as a pointer in the else clause.
That because you don't check for null in your else part.
It should be:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null)
{
//...
}
else
{
if (caseXObj != null)
{
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
}

Java: avoid checking for null in nested classes (Deep Null checking)

Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
No, can't change the structure. It's from a service I don't have control over.
No, I can't use Groovy and it's handy "Elvis" operator.
No, I'd prefer not to wait for Java 8 :D
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
You can use for:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
optional equivalent:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
Your code behaves the same as
if(family != null &&
family.getPeople() != null &&
family.people.get(0) != null &&
family.people.get(0).getAddress() != null &&
family.people.get(0).getAddress().getPostalCode() != null) {
//My Code
}
Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.
If, in case, you are using java8 then you may use;
resolve(() -> people.get(0).getAddress().getPostalCode());
.ifPresent(System.out::println);
:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
REF: avoid null checks
The closest you can get is to take advantage of the short-cut rules in conditionals:
if(family != null && family.getPeople() != null && family.people.get(0) != null && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
By the way, catching an exception instead of testing the condition in advance is a horrible idea.
I personally prefer something similar to:
nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))
public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
try {
function.apply(supplier.get());
} catch (NullPointerException n) {
return null;
}
}
or something like
nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())
public static <T> T nullSafeGetter(Supplier<T> supplier) {
try {
return supplier.get();
} catch (NullPointerException n) {
return null;
}
}
Best part is the static methods are reusable with any function :)
You can get rid of all those null checks by utilizing the Java 8 Optional type.
The stream method - map() accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the neath.
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
We also have another option to achieve the same behavior is by utilizing a supplier function to resolve the nested path:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
How to invoke new method? Look below:
Outer obj = new Outer();
obj.setNested(new Nested());
obj.getNested().setInner(new Inner());
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
Instead of using null, you could use some version of the "null object" design pattern. For example:
public class Family {
private final PersonList people;
public Family(PersonList people) {
this.people = people;
}
public PersonList getPeople() {
if (people == null) {
return PersonList.NULL;
}
return people;
}
public boolean isNull() {
return false;
}
public static Family NULL = new Family(PersonList.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
import java.util.ArrayList;
public class PersonList extends ArrayList<Person> {
#Override
public Person get(int index) {
Person person = null;
try {
person = super.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
return Person.NULL;
}
if (person == null) {
return Person.NULL;
} else {
return person;
}
}
//... more List methods go here ...
public boolean isNull() {
return false;
}
public static PersonList NULL = new PersonList() {
#Override
public boolean isNull() {
return true;
}
};
}
public class Person {
private Address address;
public Person(Address address) {
this.address = address;
}
public Address getAddress() {
if (address == null) {
return Address.NULL;
}
return address;
}
public boolean isNull() {
return false;
}
public static Person NULL = new Person(Address.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
etc etc etc
Then your if statement can become:
if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...}
It's suboptimal since:
You're stuck making NULL objects for every class,
It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and
There are potentially some funny issues with subclassing and which NULL to use.
But if you really hate your == nulls, this is a way out.
Although this post is almost five years old, I might have another solution to the age old question of how to handle NullPointerExceptions.
In a nutshell:
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
}
Since there is a lot of legacy code still in use, using Java 8 and Optional isn't always an option.
Whenever there are deeply nested classes involved (JAXB, SOAP, JSON, you name it...) and Law of Demeter isn't applied, you basically have to check everything and see if there are possible NPEs lurking around.
My proposed solution strives for readibility and shouldn't be used if there aren't at least 3 or more nested classes involved (when I say nested, I don't mean Nested classes in the formal context). Since code is read more than it is written, a quick glance to the left part of the code will make its meaning more clear than using deeply nested if-else statements.
If you need the else part, you can use this pattern:
boolean prematureEnd = true;
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
prematureEnd = false;
}
if(prematureEnd) {
System.out.println("The else part");
}
Certain IDEs will break this formatting, unless you instruct them not to (see this question).
Your conditionals must be inverted - you tell the code when it should break, not when it should continue.
One more thing - your code is still prone to breakage. You must use if(family.getPeople() != null && !family.getPeople().isEmpty()) as the first line in your code, otherwise an empty list will throw a NPE.
If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
instead you can do this
if(family?.people?[0]?.address?.postalCode) {
//do something
}
or if you need to map it to other object
somobject.zip = family?.people?[0]?.address?.postalCode
Not such a cool idea, but how about catching the exception:
try
{
PostalCode pc = people.get(0).getAddress().getPostalCode();
}
catch(NullPointerException ex)
{
System.out.println("Gotcha");
}
If it is rare you could ignore the null checks and rely on NullPointerException. "Rare" due to possible performance problem (depends, usually will fill in stack trace which can be expensive).
Other than that 1) a specific helper method that checks for null to clean up that code or 2) Make generic approach using reflection and a string like:
checkNonNull(family, "people[0].address.postalcode")
Implementation left as an exercise.
I was just looking for the same thing (my context: a bunch of automatically created JAXB classes, and somehow I have these long daisy-chains of .getFoo().getBar().... Invariably, once in a while one of the calls in the middle return null, causing NPE.
Something I started fiddling with a while back is based on reflection. I'm sure we can make this prettier and more efficient (caching the reflection, for one thing, and also defining "magic" methods such as ._all to automatically iterate on all the elements of a collection, if some method in the middle returns a collection). Not pretty, but perhaps somebody could tell us if there is already something better out there:
/**
* Using {#link java.lang.reflect.Method}, apply the given methods (in daisy-chain fashion)
* to the array of Objects x.
*
* <p>For example, imagine that you'd like to express:
*
* <pre><code>
* Fubar[] out = new Fubar[x.length];
* for (int i=0; {#code i<x.length}; i++) {
* out[i] = x[i].getFoo().getBar().getFubar();
* }
* </code></pre>
*
* Unfortunately, the correct code that checks for nulls at every level of the
* daisy-chain becomes a bit convoluted.
*
* <p>So instead, this method does it all (checks included) in one call:
* <pre><code>
* Fubar[] out = apply(new Fubar[0], x, "getFoo", "getBar", "getFubar");
* </code></pre>
*
* <p>The cost, of course, is that it uses Reflection, which is slower than
* direct calls to the methods.
* #param type the type of the expected result
* #param x the array of Objects
* #param methods the methods to apply
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T[] apply(T[] type, Object[] x, String...methods) {
int n = x.length;
try {
for (String methodName : methods) {
Object[] out = new Object[n];
for (int i=0; i<n; i++) {
Object o = x[i];
if (o != null) {
Method method = o.getClass().getMethod(methodName);
Object sub = method.invoke(o);
out[i] = sub;
}
}
x = out;
}
T[] result = (T[])Array.newInstance(type.getClass().getComponentType(), n);
for (int i=0; i<n; i++) {
result[i] = (T)x[i];
}
return result;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
and my favorite, the simple try/catch, to avoid nested null checks...
try {
if(order.getFulfillmentGroups().get(0).getAddress().getPostalCode() != null) {
// your code
}
} catch(NullPointerException|IndexOutOfBoundsException e) {}

Categories

Resources