#17440 closed enhancement (fixed)
Confusing code
Reported by: | GerdP | Owned by: | team |
---|---|---|---|
Priority: | normal | Milestone: | 19.03 |
Component: | Core | Version: | |
Keywords: | Cc: |
Description (last modified by )
I see quite a few methods with a construct like this in AbstractPrimitive
:
@Override public long getId() { long id = this.id; return id >= 0 ? id : 0; }
Why isn't field id used directly?
Attachments (1)
Change History (8)
comment:1 by , 6 years ago
Description: | modified (diff) |
---|
comment:2 by , 6 years ago
The comment says the change is about thread safety. I don't think that this code makes getId() threadsafe. If I got that right the idea is that this.id
might be changed when
return id >= 0 ? id : 0;
is executed. Not sure if that is possible but if it is we might still return a wrong result.
Same here:
@Override public final int getNumKeys() { String[] keys = this.keys; return keys == null ? 0 : keys.length / 2; }
If this.keys is changed from or to null after the local variable was set we would return a wrong result and the caller has no way to catch this situation.
I think the code is a very bad idea when it comes to thread safety.
Question is if we need correct synchronization or if we can simply remove the assignment to the local variable.
comment:3 by , 6 years ago
Summary: | Confuisng code → Confusing code |
---|
comment:4 by , 6 years ago
Sonar lint shows 83 issues for rule "Local variables should not shadow class fields". Many of them are because of this trick. I'll try to identify those "trick" lines and create a patch that removes them.
by , 6 years ago
Attachment: | 17440.patch added |
---|
comment:5 by , 6 years ago
I've now worked with this patch for a while and found no problems.
If nobody objects I'll commit this patch tomorrow.
comment:7 by , 6 years ago
Milestone: | → 19.03 |
---|---|
Type: | task → enhancement |
Added in r3348. Not sure if it's really needed.