Resolving pmd error "Avoid assignments in operands..." - pmd

$scope.nodataCheck("W",$scope.groups) && $scope.nodataCheck("b",$scope.groups) ?$scope.noWatsonData=true:$scope.noWatsonData=false;
I am getting a pmd error saying,"Avoid assignments in operands; this can make code more complicated and harder to read. This is sometime
indicative of the bug where the assignment operator '=' was used instead of the equality operator '=='."
How could I resolve this?

You are assigning true or false to $scope.noWatsonData. This is buried at the end of the line, so it's hard to see and easy to overlook. You could move the assignment to the beginning - so that it is clear, that this line determines the new value for $scope.noWatsonData:
$scope.noWatsonData = $scope.nodataCheck("W",$scope.groups)
&& $scope.nodataCheck("b",$scope.groups)
? true
: false;
As we are now merely assigning true/false according to the condition, we could assign just it without the ternary operator and make it even shorter:
$scope.noWatsonData = $scope.nodataCheck("W",$scope.groups)
&& $scope.nodataCheck("b",$scope.groups);
For reference, this is about the PMD JavaScript Rule AssignmentInOperand

Related

How does a missing boolean operator still compile?

I have code like this:
val pop: Bool = (
(fsm === Fsm.None && canPop) ||
(fsm === Fsm.Some && canPop && fooBar)
(fsm === Fsm.Other && canPop && dragonFruit) ||
(fsm === Fsm.Mom && canPop))
fsm is a ChiselEnum based state machine and the other signals are just Bools. There is a missing || on the second statement line (after fooBar). This compiles and runs, although causes a bug in the behavior. My question is... why does this compile? This doesn't seem like valid syntax. Is it?
Please help me understand this. I just spent numerous days debugging a large circuit to find this issue.
Correct Answer
The problem is that this is a bit extract. Chisel lets you do foo(bar) to extract the bit at index bar out of foo. The above code, as written, is a bit extract even though the user wants it to be a mistake.
Unfortunately, this is a known gotcha and it's not reasonable to error on this without false positives while still allowing users to use the () syntax for bit extracts.
Incorrect Original Answer
It's valid syntax per Scala rules. What's going on here is that the code is really two statements, but the indentation is confusing. It's equivalent to:
val foo = a + b // Create an immutable value equal to "a + b".
c + d // A bare statement that adds "c + d", but doesn't use the result.
Or infamous C bugs like:
if (cond)
foo();
bar(); // bar() is always executed, but the indentation is confusing.
Usually this is the type of thing that you'd notice due to a code formatter or via linting. However, the problem is common to almost every language.
Setting up Scalafmt for your project may help.

Is there way to use ternary expression with a continue statement inside a loop in Dart

I'm trying to use a ternary expression along with a continue or break construct inside a do-while loop in Dart but I get a compilation error.
do
{
expr ? print('Conditionally print something') : continue;
}while(expr == true);
The above code fails at compile-time but if I use a pair of if-else decision structure, the code works. So, the question to the community is why the ternary expression is not working along with continue or break construct?
The ternary operator takes 3 expressions in the form of (expr1) ? (expr2) : (expr3).
You can't execute statements in ternary operator, nor only in dart but in other languages also. Since break and continue are not expressions but statements they cant be used here
No, you can't do it.
continue is a Dart Statement (read below), and print is a function
First
In the Dart Language Specification section 17.23 explains how it works.
https://dart.dev/guides/language/specifications/DartLangSpec-v2.10.pdf
Search the original document, because the copy/paste doesn't seems to work well.
17.23 Conditional conditional
A conditional expression evaluates one of two expressions based on a boolean
condition.
{conditionalExpression} ::= {ifNullExpression}
(‘?’ {expressionWithoutCascade} ‘:’ {expressionWithoutCascade})?
Evaluation of a conditional expression c of the form e1?e2 : e3 proceeds as
follows:
First, e1 is evaluated to an object o1. It is a dynamic error if the runtime type of o1 is not bool. If r is true, then the value of c is the result of
evaluating the expression e2. Otherwise the value of c is the result of evaluating
the expression e3.
Second
As you can see the ternary operator requires expressions, but continue, in the same PDF of language specification is defined as an statement, a reserved word, as:
18 Statements statements
A statement is a fragment of Dart code that can be executed at run time.
Statements, unlike expressions, do not evaluate to an object, but are instead
executed for their effect on the program state and control flow
Third
in the case of print, it's taken as a function I guess, didn't find the specification. Perhaps it returns void.
We can still ask ourselves, why can't we put continue in a function, even in a lambda like () => { continue; } or similar. The short answer is that as said in the specification for the continue statement, if it's not inside a while, etc. is gonna give a compile error. And if it's inside a function, it will prevent that function to reach the return statement, and again, the ternary will expect a return value.
We can still research a little more, many things are inside the specification.
When something like this happens, you can also search without specifying the language, to get information on JAVA or C# that may help you.
Java: Ternary with no return. (For method calling)
It seems that Swift language would allow continue and break inside the ternary, as per this article - https://forums.swift.org/t/bringing-control-flow-keywords-to-the-ternary-operator/13878
Because a ternary operator is returning a value. With the following syntax:
condition ? expresion1 : expression2
which means:
If condition is true, it return expression1. If it is not it return expression2.
So, you can't use statement like this:
print('Conditionally print something')
or
continue
An expression evaluates to a value. A statement does something.

Why do I get this compiler error with the djb2 hash function

I copied and pasted the widely available code for the djb2 hashing function, but it generates the error shown below (I am using the CS50.ide, which may be a factor). Since this error IS fixed by a second set of parentheses, can someone explain why those aren't in the code I find everywhere online?
dictionary.c:67:14: error: using the result of an assignment as a condition without
parentheses [-Werror,-Wparentheses]
while (c = *word++)
~~^~~~~~~~~
dictionary.c:67:14: note: place parentheses around the assignment to silence this
warning
while (c = *word++)
^
( )
dictionary.c:67:14: note: use '==' to turn this assignment into an equality comparison
while (c = *word++)
^
==
= is used for setting variables to a value. == is the relational operator used for comparing the equality of values. Perhaps you are finding the C++ version of the function. Perhaps it is the IDE compiler rules/config.+
I understand about = vs ==. My question was how come i get the compiler error with code that is correct, since it is a well established hash function.
turns out is related to the cs50 makefile being more stringent than clang on it's own. needlessly frustrating.

Need an explanation for a confusing way the AND boolean works

I am tutoring someone in basic search and sorts. In insertion sort I iterate negatively when I have a value that is greater than the one previous to it in numerical terms. Now of course this approach can cause issues because there is a check which calls for array[-1] which does not exist.
As underlined in bold below, adding the and x > 0 boolean prevents the index issue.
My question is how is this the case? Wouldn't the call for array[-1] still be made to ensure the validity of both booleans?
the_list = [10,2,4,3,5,7,8,9,6]
for x in range(1,len(the_list)):
value = the_list[x]
while value < the_list[x-1] **and x > 0**:
the_list[x] = the_list[x-1]
x=x-1
the_list[x] = value
print the_list
I'm not sure I completely understand the question, and I don't know what programming language this is, but most modern programming languages use so-called short-circuit Boolean evaluation by default so that the logical expression isn't evaluated further once the outcome is known.
You can use that to guard against range overflow, like this:
while x > 0 and value < the_list[x-1]
but the check of x's range here must come before the use.
AND operation returns true if and only if both arguments are true, so if one of arguments is false there's no point of checking others as the final value is already known at that point. As for your example, usually evaluation goes from left to right but it is not a principle and it looks the language you used is not following that rule (othewise it still should crash on array lookup). But ut may be, this particular implementation optimizes this somehow (which IMHO is not good idea) and evaluates "simpler" things first (like checking if x > 0) before it look up the array. check the specs why this exact order works for you as in most popular languages you would still crash if test x > 0 wouldn't be evaluated before lookup

object == nil or nil == object to check whether an object is nil?

While checking whether an object is nil, someone use 1:
if (object == nil) {
//...
}
someone use 2:
if (nil == object) {
//...
}
Any difference between 1 and 2? Which one is better?
The difference is mainly that if you mistakingly forget a = e.g like this
(nil = myObject)
you will get an error cause you can't assign a value to nil. So it is some kind of faile-safe.
The use of nil == object is actually an idiom to prevent the unlucky case where you miss a = in your expression. Example, you want to write:
if (object == nil)
but write:
if (object = nil) {
this is a typical error and one that is very difficult to track down, since the assignment has also a value as an expression and thus the condition will evaluate to false (no error), but you will also have wiped out your object...
On the other hand, writing
if (nil == object)
you ensure that that kind of error will be detected by the compiler since
if (nil = object)
is not a regular assignment.
Actually, modern compilers (default settings) will provide a warning for the kind of "unintended" assignment, ie:
if (object = nil) {
will raise a warning; but still this can be tricky.
As others pointed out, they are equivalent. There is also another way to do it:
if (!object) {
// object is nil
}
The reason some developers prefer "Yoda conditionals" is that it's less likely to inadvertently write if (object = nil) (note the assignment).
This is not an issue any more since compilers warn when assigning in a conditional expression without extra parentheses.
Since Yoda conditionals are less readable they should be avoided.
They are equivalent. Back in the days it was common to write if (CONST == variable) to reduce the risk of accidental assignment. E.g. if (variable = CONST) would assign a constant to the variable and the if-statement would evaluate as true or false depending on the value of the constant, not the variable.
Nowadays, IDEs and compilers will usually be smart enough to issue a warning on such lines. And many people prefer the first version due to readability. But really it's a matter of style.
best practice when using the comparison operator == is to put the constant on the left of the operand. in this way it is impossible to accidentally mistype the assignment operator instead of the comparison.
example:
( iVarOne == 1 )
is functionally equal to
( 1 == iVarOne)
but
( iVarOne = 1 )
is much different than
( 1 = iVarOne )
this best practice works around the fact that compilers do not complain when you mistype an assignment for a comparison operator...
Nope, only in readability I prefer the first one, while some other developers may prefer the other.
Its just a coding style issue, it has no technical difference at all.
Some may say that the second is better, since it is more explicit, the nil comes first so its easier to note that we are testing for nil, but again it depends on the developer taste.
There is no difference at all. It's all about readability. If you want to write a clean code, you should take care of this.
If you place the "Object" to the right of the evaluation, it becomes less apparent what are you really doing.
It is not NIL, it is NULL.
They are one and the same. The == operator is a comparison operator. As a general trend, we use (object==NULL)