Sonar violation on "disallowed assignment of parameters" - java

I have the following code and I got an sonar violation error: disallowed assignment of parameters
What is the best way to fix this?
/**
* #param lastAccessTime the lastAccessTime to set
*/
public void setLastAccessTime(Date lastAccessTime)
{
this.lastAccessTime = lastAccessTime == null ? null : new Date(lastAccessTime.getTime());
}

I suspect one of 2 things are happening here:
1 - There is a bug in the checkstyle plugin
2 - The code sonar analysed is not quite the code you posted here
I believe that violation should apply in the following case:
/**
* #param lastAccessTime the lastAccessTime to set
*/
public void setLastAccessTime(Date lastAccessTime)
{
lastAccessTime = lastAccessTime == null ? null : new Date(lastAccessTime.getTime());
}
So when you are reassigning the method parameter it would be expected, but in your example you are not, you are assigning it to a class field so it should be ok.
Try changing the method parameter to final and see if you still see the violation.

Related

Why does spring boot libraries like spring-security have assertions in /src/main and not exceptions thrown for such validations?

While going across many modules from spring boot repositories, I could find assertions in /src/main/ like here as below in file,
public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
Set<String> scopes) {
super(tokenValue, issuedAt, expiresAt);
Assert.notNull(tokenType, "tokenType cannot be null");
this.tokenType = tokenType;
this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
}
Isn't it should be using exceptions to be thrown instead for all such validations under /src/main/.
As far as I've read, assertions are meant to be used with test cases under /src/test/.
This does throw an exception. The word "assertion" simply means "declare that something should be true", and this can happen in testing or at runtime. You're merging the concepts of assertions in general with the specific tools of the assert keyword in Java or test-assertion libraries like AssertJ.
In this particular case, the Assert in question is org.springframework.util.Assert:
/**
* Assert that an object is not {#code null}.
* <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
* #param object the object to check
* #param message the exception message to use if the assertion fails
* #throws IllegalArgumentException if the object is {#code null}
*/
public static void notNull(#Nullable Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
Similar facilities are available with Guava Preconditions and commons-lang Validate; they're not called "assert", but they have identical semantics.

NoraUI - Null Pointer Exception while using a customDataProvider as Input and Output

I have a problem when i try to use a CustomDataProvider as Input and Output. At some point in the scenario, a NPE exception is thrown.
Edit 1 : I've already read What is a NullPointerException, and how do I fix it? : I understand what is a NPE and how to resolve it. What i do not understand in my case is why there is one happening at that moment of the execution and with this particular object in my case. I am not an expert of the NoraUI Framework. When I looked at existing dataProvider they never manipulate indexData object, so I did not too. I do not know how they are handled and when they are initialized. That is why I am asking the question of why it is happening at this moment and if I forgot something to someone with more experience. Sorry if it was not clear. it is a question more related to the NoraUI Framework than a pure Java one.
The Exception :
The scenarioInitiator execution is going well with the CustomDataProvider : the data is well generated and written on the Gherkin. But just at the beginning of the launch of the scenario, the exception is thrown :
[2017-08-16 15:37:28]: ********************************************************************************************************
[2017-08-16 15:37:28]: * *
[2017-08-16 15:37:28]: * Scénario: [#scenario] étape 1 sur 0 avec 0 erreur(s) et 0 alerte(s). Il reste 0s *
[2017-08-16 15:37:28]: * *
[2017-08-16 15:37:28]: ********************************************************************************************************
Failed scenarios:
steps/scenarios/scenario.feature:4 # Scenario: scenario
1 Scenarios (1 failed)
28 Steps (28 skipped)
5m52.930s
java.lang.NullPointerException
at noraui.exception.Result$Success.<init>(Result.java:32)
at noraui.application.steps.CucumberHooks.setUpScenario(CucumberHooks.java:44)
With a little more research with the debug, it seems the exact line that is provoking the Exception is the condition of the for loop in the first constructor of the noraui.exception.Result$Success object :
public static class Success<O> extends Result {
private final O object;
private static final Logger logger = Logger.getLogger(Success.class.getName());
public Success(O object, String message) throws TechnicalException {
this.object = object;
this.message = message;
for (Integer i : Context.getDataInputProvider().getIndexData(Context.getCurrentScenarioData()).getIndexes()) {
Context.getDataOutputProvider().writeSuccessResult(i);
}
logger.info(message + " [" + success() + "]");
}
public O success() {
Optional<O> o = Optional.ofNullable(object);
return o.isPresent() ? o.get() : null;
}
}
I suppose it have something to do with the IndexData that are declared in the DataProvider Object (which is extended by CustomDataProvider which is in turn extended by my customDataProvider). But I just can't see why it would fail as in my case I used the super method, just as the other common DataProvider (Excel, DB, etc).
Custom Data Provider :
My custom data provider launch multiples query with some being modified depending of what the first query return. The final result of those queries is stored into the ArrayList<ArrayList<String>> dataTable variable. the row of the data are the following : | Offer | Product | Items | Results |
So my question is :
Why does using my custom data provider throw this NPE while with other DataProvider, it does not. As i do not see any of them having custom way of handling DataIndex.
Your problem seems to occur because of this part of code:
getIndexData(Context.getCurrentScenarioData())
getIndexData returns null for the current retrieved Context.getCurrentScenarioData();
If you created an DataInputProvider, you should extend your class from CommonDataProvider and override getModel() method as following:
/**
* {#inheritDoc}
*/
#Override
public Class<Model> getModel(String modelPackages) throws TechnicalException {
return null;
}
The getNbLines() method should be also be redefined by returning the number of data lines used as input (including column names line).
In fact, these two methods are required in Context class to initialize scenarios data indexes that are used for writing results.
Hoping this helps

Should param validation be performed lazily

Following is the code for lazy intialization of an instance member. This leaves me with question of when to perform parameter validation. In the code are 2 differenct functions performing NPE check one delays it, other does not. I chose the first option, but just curios to know whats the industry wide convention / best practice.
public class FreeMain {
private List<Integer> fooList;
FreeMain ( ) { }
/**
* This code does a check null pointer kind of just in time.
*
* #param barList
*/
public void putListExceptionCheckDoneLater(List<Integer> barList) {
if (this.fooList == null) {
if (barList == null) throw new NullPointerException();
this.fooList = barList;
}
}
/**
* In the even that fooList != null,
* throwing an exception would be of no benefit,
* since regardless of input, null or not, net effect would still be a no-op.
*
* #param args
*/
public void putListExceptionCheckDoneBefore(List<Integer> barList) {
if (barList == null) throw new NullPointerException();
if (this.fooList == null) {
this.fooList = barList;
}
}
public static void main(String[] args) {
}
}
This code is custom designed to ask a specific doubt, so please refrain from questions like why not use constructor to pass list ? etc, or suggest code improvements which are not connected to this question.
I can't see the point of deferring parameter validation, certainly for something as light-weight as checking for null. And it has some definite downsides:
(True) lazy validation makes your code more complicated.
(True) lazy validation is going to lead to validation errors popping up when it is too late to do anything about them.
Having said that, the logic of your example doesn't make much sense to me. The real difference between the two versions is that the first one doesn't check its argument at all if it isn't going to use it. This is NOT what "lazy" means. This is just doing things in a different order ... and giving different outcomes as a result.
(For what it is worth, I would prefer to check that barList is not null all of the time ... on the assumption that it is never meaningful for the parameter to be null. That way is likely to pick up bugs earlier.)
For the record, this is what true lazy validation might look like:
public class LazyValidationExample {
private List<Integer> fooList;
public void putListExceptionCheckDoneLater(List<Integer> barList) {
this.fooList = barList;
}
public List<Integer> getList() {
if (this.fooList == null) throw new NullPointerException();
return this.fooList;
}
...
}

Checkstyle working differently for same condition

On applying check style i am getting " hides a field" if the name of formal and actual parameters are same.
private String limitedDimensionId;
/**
* Sets the limited dimension id.
*
* #param limitedDimensionId
* the new limited dimension id
*/
public void setLimitedDimensionId(final String limitedDimensionId) {
this.limitedDimensionId = limitedDimensionId;
}
However i am not getting the same issue in the following case:
private boolean fallBack;
/**
* #param isFallBack
* the isFallBack to set
*/
public void setFallBack(final boolean isFallBack) {
this.fallBack = isFallBack;
}
Both the conditions appear same to me. Still the discrepancy. Usually i change the name of the parameter variable to resolve this check style issue. But looking at the other case i am getting a hint that a more elegant solution is available. Any insights?
The variable names are different:
fallBack vs isFallBack
Usually i change the name of the parameter variable to resolve this check style issue
That's correct solution.
I would agree that giving them different names is more appropriate, however the "this" keyword in the "this.limitedDimensionid" should avoid the "hides a field" error. That's what it's for...

Java - Get/set methods receiving and returning "null"

I'm a beginner in Java. I'm trying, for training purpose, to build myself a chess game application. Within my class Case, that will be used to instanciate all the 64 cases of my board, I write get/set methods to find if there's a Piece occupant in the instances of the case.
I read that returning "null" is a bad practice, so I throw an exception instead to signify that the case is free. But, I wonder how to set the occupant's pointer to "null"; can I simply push "null" as a parameter when I will call this method?
Also, could taking/returning "null" be an acceptable/good practice?
public Piece getOccupant(){
if (this.occupant == null)
throw new IllegalArgumentException(this.occupant + " is Empty");
return this.occupant;
}
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
Thanks!
[Update]
Thanks to all of your for your comments, ideas, corrections and recommendations. Here is the updated version of my code for this part, and I feel satisfied with it, as it served its purpose (increase my understanding thru practice).
/*
* Modifiers of Occupant
*/
/**
* Used to find if a Piece is located in this Cell
* #return a Piece reference to the occupant. Will send a
* null pointer if cell is empty
*/
public Piece getOccupant(){
return this.occupant;
}
/**
* Used to set a new occupant in the Cell.
* #param newOccupant is a reference to a Piece instance,
* and should be set to null if the cell is emptied, or using
* the method clear().
*/
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
/**
* Used to verify if a Cell is empty of any occupant
* #return true if cell is empty.
*/
public boolean isEmpty(){
if(this.occupant == null)
return true;
return false;
}
/**
* Free the cell of any occupant, if any were
*/
public void clear(){
this.occupant = null;
}
A space on the board being unoccupied is not exceptional. Its normal and will always be true for the majority of the board. You should not be throwing exceptions here; exceptions should only be thrown for an unexpected event that signify a significant problem with what you are trying to do.
You can certainly pass null to a setter (except for a primitive type like int/long).
It might be better to add some convenience methods, an isEmpty method to your Space class:
public boolean isEmpty(){
if (this.occupant == null)
return true;
return false;
}
and also perhaps a clear method
public void clear() {
this.occupant = null;
}
that way you don't have to test on the nullity of the getter result, and you don't need to pass null to set -- this has the added benefits of being easily testable, and creates a API that is meaningful to your Space class.
If you want to forbid null values, you should do it on the setter method:
public void setOccupant(Piece occupant) {
if (occupant == null) throw new NullPointerException("occupant");
this.occupant = occupant;
}
Note that some people prefer to throw IllegalArgumentException. Either way, the point is to "fail fast" as soon as someone sets a forbidden value.
Having said all of that, a chess board certainly can have empty positions, so allowing null seems to make more sense.
I suggest you read "Effective Java, 2nd Edition" by Josh Bloch.
Where did you read that recommendation? In my opinion, there is absolutely nothing wrong about returning null, provided that null conveys some useful information and does not indicate a severe error condition. In this case, it is perfectly normal for a chess cell to not contain a piece, and I would definitely expect getOccupant() to return null in that case.
If the caller is aware of NULL return values, it's not bad to return NULL values by callee.
Instead of returning null or throwing an exception, you should create a class "Empty", "None", "Void", something like that, that you would assign to all your Case that are empty.
small suggestion
no need of if block, you can simplify your code by simply returning the output of expression
public boolean isEmpty(){
return this.occupant == null
}

Categories