Re: switch using strings



On 3/2/11 9:43 PM, javax.swing.JSnarker wrote:
On 02/03/2011 10:53 PM, Peter Duniho wrote:
It does, and yes…if those assumptions are valid, it can address the
problem even without interfering with other code. But so what? It
doesn't change the fact that there's a way to write the code such that
it _looks_ correct, but which actually is not.

That's always going to be possible in any nontrivial programming language.

Some language features make it easier to do than others.

It might be useful if the compiler emitted a warning when synchronizing
on a non-final instance variable.

That would be silly.

However (for example) C# _does_ in fact disallow unboxed value types in a "lock" statement, for this very reason.

On the other hand, C# doesn't have quite precisely the same auto-boxing issue, because due to its integrated support of value types, there isn't this "two different kinds of 32-bit integer" issue in the first place.

Since Java also doesn't have operator overloading for classes, even if
Integer were mutable (which would be a really bad idea in and of itself)

You'd have to use a new, mutable Integer-like class instead of Integer
itself, obviously.

It would still be a bad idea to auto-box into a mutable reference type, whatever you called that type.

the use of the ++ operator would result in auto-boxing and a new object
instance anyway.

+ is overloaded for java.lang.String. That Java does not permit the
*user* to add operator overloads does not mean the *language designers*
cannot do so.

The string type is a very special case. Given the language designers were not inclined to overload ++ for the current Integer type, I have a hard time imagining that they would overload it for any hypothetical replacement for that type.

I must wonder why whoever wrote that code didn't just use
AtomicInteger...

Or an "int" instead of an "Integer".

You can't synchronize on an "int".

Nor would you bother to synchronize on an AtomicInteger. So? The point is that there are better ways to write the code that would not lead someone into the trap in the first place.

Pete
.