"Field can be converted to a local variable" / "Field can be local"

Hi,

I believe this warning is false, at least in some cases.

I have places where a field is initialized by a call to a method and where that field is used only in a single method, leading to the triggering of this inspection.

However, the inspection's validity seems to overlook possible side-effects, non-idempotency and execution costs of the method call used to supply the initializing value for the field in question.

Am I mistaken about this?


Randall Schulz

Edited by: Randall Schulz on Apr 29, 2008 12:25 PM — Changed the oxymoronic "local field" to "field" in the 2nd paragraph.

8 comments
Comment actions Permalink

Yep,
in general this transformation is not 100% preserving code semantics sometimes as you state. However I believe it should be flagged for your review as a potentially unnecessary field. This is a classical non black-and-white case where we believe most of the time it is black. If you don't think this warning is relevant, just suppress it.

0
Comment actions Permalink

On a second thought, however, it seems really dangerous suggestion. This 'improvement' should probably be rolled back:(

0
Comment actions Permalink

Hello Randall,

I believe this warning is false, at least in some cases.

I have places where a local field is initialized by a call to a method
and where that field is used only in a single method, leading to the
triggering of this inspection.

However, the inspection's validity seems to overlook possible
side-effects, non-idempotency and execution costs of the method call
used to supply the initializing value for the field in question.

Am I mistaken about this?


There is no way for IntelliJ IDEA to analyze all of these factors automatically.
That's why this, like any other inspection, is a suggested fix which you
must accept manually, or suppress if it's not appropriate in the given case.

--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
http://www.jetbrains.com/
"Develop with Pleasure!"


0
Comment actions Permalink

Dmitry,
I believe Randall means a specific case that I realized not long ago. In this case the inspection is indeed not appropriate.

0
Comment actions Permalink

Can you give us an example about what danger you're talking?

Eugene Vigdorchik wrote:

On a second thought, however, it seems really dangerous suggestion. This 'improvement' should probably be rolled back:(

0
Comment actions Permalink

Ouch, I cannot give you an example. The logic to introduce local initialized with field initializer I implemented not long ago works only for constructors - so no idempotence or any other problems Randall lists.
So I'm a bit lost now.

0
Comment actions Permalink

How do you suppress this error specifically.  I am currently forced to use @SuppressWarnings("all").

0
Comment actions Permalink

Figured it out
@SuppressWarnings("FieldCanBeLocal")

0

Please sign in to leave a comment.