Reputation: 418
I'm trying to toggle a class level boolean called toggle
like so:
public void myClass() {
private boolean toggle = false;
public void process(){
while (x < y) {
if (toggle()){
//do some stuff
} else {
//do some other stuff
}
}
}
private boolean toggle() {
return this.toggle = this.toggle ? false : true;
}
}
but SONAR complains about return this.toggle = this.toggle ? false : true;
saying "Inner assignments should be avoided." If i refactor this to pass the class level boolean into the toggle()
method it doesn't work and always returns true. Is there an elegant way of achieving the same without SONAR complaining?
Upvotes: 0
Views: 1614
Reputation: 178313
You can accomplish this task by breaking up the purpose of the method into the 2 parts:
Passing an instance variable into the method as an argument won't work; the method will get a copy of the value; the original won't change.
Simpler code is better and more readable.
I avoid attempting to mix the ternary operator with an assignment, because that would attempt to do two things at once, and it can be unclear, especially without memorizing the order of precedence between the assignment operator (=) and the ternary operator (?:).
Also, the ternary operator is unnecessary; the negation operator !
will toggle a boolean for you.
private boolean toggle() {
this.toggle = !this.toggle;
return this.toggle;
}
If you happen to want to use the previous value of the boolean, store it into a local variable first before changing the value.
private boolean toggle() {
boolean prevToggle = this.toggle;
this.toggle = !this.toggle;
return prevToggle;
}
While I haven't used SonarQube, this change should eliminate the warning about inner assignments, and it should make your code clearer and easier to maintain.
Upvotes: 1