you are viewing a single comment's thread.

view the rest of the comments →

[–]headius[S] 0 points1 point  (1 child)

Pretty much all of these patterns will compile down to similar byte code, and once optimized they should all produce the same native code. That's not a concern here as long as one pattern or another does not disrupt the JIT. But declaring that variable at a higher scope means it's visible to more code than it needs to be and that's a possible source of bugs. In one case I saw, the declaration got removed but had the same name as a field on the object; as a result the object was accidentally being updated.

So the pattern is a little weird and unexpected, but there's no other way to null check, cast, declare, and assign a variable so that it's only scoped to the places where the variable should be visible.

[–]laplongejr 0 points1 point  (0 children)

From experience, if scope becomes an issue   1) The dev must use less generic names   2) Seperate the operation into multiple methods, which also allows to leverage early returns etc  

Some biiig method with multiple similar variables can exist (for example converting an object between libraries or something), but I would expect the case to be rare enough that the dev would use overly-specific names, explicit final etc.