classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Proposed coding standard updates


From: Thomas Zander
Subject: Re: Proposed coding standard updates
Date: Sat, 3 Apr 2004 14:56:47 +0200
User-agent: KMail/1.6.1

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Saturday 03 April 2004 12:37, Andrew Haley wrote:
>  > > > Here, `cal' is a local variable and YEAR is a static field in
>  > > > Calendar.  This is valid code, but I find it somewhat confusing;
> the > > > stuff before "." is evaluated for side effects only.  I'd
> rather we > > > not use static members with a non-static qualifier, and
> instead write > > > `Calendar.YEAR'.
>
> I think the writer's intention was to show that the YEAR field was in
> the class of the member `cal'.  I don't think you can determine with a
> simple one-size-fits-all rule whether this is never an appropriate
> thing to do.

Remember that javac gives errors when the 'cal' variable has not been 
initialized? Even while the used member is a static.
The reason it does that is since a class that extends Calendar could have 
re-defined the static and the code will use a different value.

To see why; you have to know a little bit more about how the runtime 
interprets static members.

Consider this:
bla() {
        boolean var = Boolean.TRUE.booleanValue();
}

At runtime 'var' will be allocated on the stack.
Then the class 'Boolean' will get parsed and initialized.
Then the TRUE member will be instanciated and placed on the class.
After which the newly created instance 'TRUE" will be used to call 
booleanValue() upon.

Notice that in case of a basetype this is slightly different.


So, to avoid NullPointerExceptions, wierd assignments etc, it is NEVER a 
good idea to use an instance to reach a static. Most Java IDEs rightfully 
bark at such usage since they create misconceptions and real bugs.

I fixed quite some silly bugs in our companies library using IDEA and the 
detection for this kind of mistakes.

I suggest to run http://findbugs.sourceforge.net/ to search for this (and 
many other) kind of bugs.

- -- 
Thomas
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAbrSPCojCW6H2z/QRAr+PAJ9oSnDRHTjVJELw/pQ960t0ESK9LwCfaV9M
9BXNlgSMyzcYqT1YcaYoNYE=
=z8Ol
-----END PGP SIGNATURE-----




reply via email to

[Prev in Thread] Current Thread [Next in Thread]