3 ms·
One would hope at some point a tool would warn you about this since clearly it could optimize (int) Math.random() to just 0. [queue debate about tools that hol
by ChuckMcM 16y ago
One would hope at some point a tool would warn you about this since clearly it could optimize (int) Math.random() to just 0.
[queue debate about tools that hold your hands vs understanding what you are actually writing]
I wonder if they did the search for if (x = y) bug pre-gcc-4.x-warn what sort of numbers they would get.
- derleth 16y ago> queue Speaking of common bugs... (The word you're looking for is 'cue'.)
- redthrowaway 16y agoUnless we're talking about adding the debate to the queue of debates we're having, that is. Even then, I suppose, it should be enqueue...
- nolanw 16y agoWere you actually confused, or are you just picking nits? If the latter, then it's not really a bug is it.
- kwantam 16y agoActually, nits are bugs. They just haven't hatched yet. [1] http://en.wikipedia.org/wiki/Louse http://en.wikipedia.org/wiki/Louse
- Carlfish 16y agoI believe this is the tool you are looking for. http://findbugs.sourceforge.net/bugDescriptions.html#RV_01_TO_INT http://findbugs.sourceforge.net/bugDescriptions.html#RV_01_T...
- nradov 16y agoI'm amazed to still find Java programmers who don't run Findbugs on all their code. It's free, fast, and has a low rate of false positives.
- erez 16y ago"queue debate about tools that hold your hands vs understanding what you are actually writing" For a start, explain why, in Java, (int) Math.random() is a bug. A programmer that happens upon this thread, now knows "this is bad", but has no clue why. A tool will only make the programmer even more reliant on tools and IDEs, so this kind of bug will be eliminated, but the frame of mind that spawned it will live on.
- Carlfish 16y agoFindbugs, the popular Java tool I linked to in another comment, explains the bug like this: "A random value from 0 to 1 is being coerced to the integer value 0. You probably want to multiple the random value by something else before coercing it to an integer, or use the Random.nextInt(n) method." That's about as good an explanation as you'd get from anyone. The way I see it is this. Simple bugs like this happen because _human beings are flawed._ All it takes is a momentary lapse of concentration and you've put the cast in the wrong place in a method you don't write a test for because you're in a hurry, and all it's doing is generating a random number with a standard API so why bother? (Or it's something you wouldn't normally even test for, like assuming something is re-entrant when it isn't) We're inevitably going to make a certain number of mistakes a day, and it's our duty to put systems into place that catch those mistakes before they cause any more damage than they should.