I have been working with IntelliJ which keeps making suggestions to
improve you code. One thing it likes to do is add finals wherever it
can.
This presumably helps the compiler generate better code at it makes
clear to maintenance programmers what you can count on staying fixed.
There are two idioms you might not know that allow final:
private static final int x;
static {
x = complicated Expression involving other constants;
}
This is good when order of initialisation matters. If you put the
code inside a static init, the order can't be ruined by a
code-beautifier that alphabetises or otherwise reorders fields.
also
private final int x;
Constructor ( )
{
x = something;
}
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
|
0
|
|
|
|
Reply
|
my_email_is_posted_on_my_website (4730)
|
3/7/2006 7:42:38 AM |
|
Be careful, though, in both cases the field may be exposed to external
viewers before being assigned, and this will have the most undesirable
effect of having the "final" value change.
|
|
0
|
|
|
|
Reply
|
schulz.stefan (81)
|
3/7/2006 8:22:12 AM
|
|
Roedy Green wrote:
> private final int x;
>
> Constructor ( )
> {
> x = something;
> }
Sometimes this is not possible, for instance if "something" is
declared to throw an exception. The common pattern is then to
first assign to a temporary variable before assiging to the
class variable, as the final can be assigned just once inside
the ctor:
Constructor()
{
int tmp;
try {
tmp = something;
}
catch (Exception e) {
tmp = somethingElse;
}
x = tmp;
}
|
|
0
|
|
|
|
Reply
|
jacob9706 (365)
|
3/7/2006 8:34:40 AM
|
|
Roedy Green wrote:
>
> This presumably helps the compiler generate better code at it makes
> clear to maintenance programmers what you can count on staying fixed.
Slightly better code from the java source->byte code compiler for static
fields (constant expressions). From 1.5 byte code->machine code compiler
can make assumptions that final fields do not have to be reread after
synchronisation and volatile operations. Final local variables make no
difference from a performance perspective.
> private static final int x;
>
> static {
>
> x = complicated Expression involving other constants;
> }
Rather irritatingly you can't qualify the assignment for statics:
class MyClass {
private static final OtherClass thing;
static {
OtherClass thing = new OtherThing();
... configure thing ...
MyClass.thing = thing; // compile error
}
...
}
IIRC, in Effective Java, Josh Bloch recommends using static creation
methods instead:
class MyClass {
private static final OtherClass thing = descriptiveMethodName();
...
private static OtherClass descriptiveMethodName() {
OtherClass thing = new OtherThing();
... configure thing ...
return thing;
}
}
> This is good when order of initialisation matters. If you put the
> code inside a static init, the order can't be ruined by a
> code-beautifier that alphabetises or otherwise reorders fields.
If you put all static initialisation in static initialisers. Code
reordering is still likely to make a mess if you go for static
initialisers next to declarations.
> private final int x;
>
> Constructor ( )
> {
> x = something;
> }
I much prefer to always qualify instance field in constructors (and
setters) with this..
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
|
|
0
|
|
|
|
Reply
|
usenet120 (1481)
|
3/7/2006 10:20:39 AM
|
|
Roedy Green wrote:
> private static final int x;
>
> static {
>
> x = complicated Expression involving other constants;
> }
>
Careful with that - if "complicated expression" throws an exception,
you'll get an ExceptionInInitializerError, and the class won't be
loaded - and if your app survived that, next time
you try to use that class withing the app you'll get a
NoClassDefFoundException.
(somebody please correct me if I'm wrong)
|
|
0
|
|
|
|
Reply
|
jagonzal (30)
|
3/7/2006 12:44:23 PM
|
|
jagonzal@gmail.com wrote:
> Roedy Green wrote:
>> private static final int x;
>>
>> static {
>>
>> x = complicated Expression involving other constants;
>> }
>>
>
> Careful with that - if "complicated expression" throws an exception,
> you'll get an ExceptionInInitializerError, and the class won't be
> loaded - and if your app survived that, next time
> you try to use that class withing the app you'll get a
> NoClassDefFoundException.
I think it wont compile if the static block can throw an exception.
/tom
|
|
0
|
|
|
|
Reply
|
tom324 (214)
|
3/7/2006 3:36:26 PM
|
|
Roedy Green wrote:
> I have been working with IntelliJ which keeps making suggestions to
> improve you code. One thing it likes to do is add finals wherever it
> can.
>
> This presumably helps the compiler generate better code at it makes
> clear to maintenance programmers what you can count on staying fixed.
>
> There are two idioms you might not know that allow final:
>
>
> private static final int x;
>
> static {
>
> x = complicated Expression involving other constants;
> }
>
> This is good when order of initialisation matters. If you put the
> code inside a static init, the order can't be ruined by a
> code-beautifier that alphabetises or otherwise reorders fields.
>
> also
>
> private final int x;
>
> Constructor ( )
> {
> x = something;
> }
I am not sure I understand what you are getting in this post.
You are listing three points 1) intellij and finals, 2) musings on
finals in compilation and 3) idioms for using final.
AFAICT, you are not making a suggestion or conclusion, could you please
elaborate.
/tom
|
|
0
|
|
|
|
Reply
|
tom324 (214)
|
3/7/2006 3:52:53 PM
|
|
Hi,
tom fredriksen wrote:
>> Roedy Green wrote:
>>
>>> private static final int x;
>>>
>>> static {
>>>
>>> x = complicated Expression involving other constants;
>>> }
>>>
>>
>> Careful with that - if "complicated expression" throws an exception,
>> you'll get an ExceptionInInitializerError, and the class won't be
>> loaded - and if your app survived that, next time
>> you try to use that class withing the app you'll get a
>> NoClassDefFoundException.
>
> I think it wont compile if the static block can throw an exception.
It will compile and the static block can throw a RuntimeException.
Ciao,
Ingo
|
|
0
|
|
|
|
Reply
|
ihomann_spam (336)
|
3/7/2006 5:04:56 PM
|
|
On Tue, 07 Mar 2006 16:52:53 +0100, tom fredriksen <tom@nospam.org>
wrote, quoted or indirectly quoted someone who said :
>I am not sure I understand what you are getting in this post.
>You are listing three points 1) intellij and finals, 2) musings on
>finals in compilation and 3) idioms for using final.
>AFAICT, you are not making a suggestion or conclusion, could you please
>elaborate.
There is nothing to explain. You understand perfectly.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
|
0
|
|
|
|
Reply
|
my_email_is_posted_on_my_website (4730)
|
3/7/2006 5:19:27 PM
|
|
Hi Roedy,
first thanks a lot for mindprob.com!
> I have been working with IntelliJ which keeps making
> suggestions to improve you code. One thing it likes to
> do is add finals wherever it can.
If you let him do it (which I certainly do). But you can customize
everything (like asking him to propose or not final for method
parameters, etc.): convenient for people who have their preferred
way of doing it (and who thinks that it's better than Jetbrain's
default config, but that is another topic ;)
> This presumably helps the compiler generate better code at
> it makes clear to maintenance programmers what you can
> count on staying fixed.
And it surely helps IntelliJ's own (incredible IMHO) real-time
source code parser to make very relevant comments like
"condition xxx will always be true" or "code here will never
be executed" etc.
I'm not talking about the usual compiler messages, but
messages made possible by IDEA's own Java source
tree framework (available to anyone willing to write
plugins for IDEA btw).
I've had case where I'd just stop, think a little bit and
realize "oh my, IntelliJ is right!" just followed by
"how could he know that!?". Then I realize that it's
been analyzing the code quite extensively and used
all the infos it had (like that tiny little "final" modifier
here and there) to eventually make its correct statement.
What I'm saying is that I *know* what IDEA's parser
is capable of, but once it while it still surprises me.
IDEA's parser is good, very good. And any hint you give
hime just makes him better.
Bye and thanks again for mindprob,
Driss
|
|
0
|
|
|
|
Reply
|
neuneudr (93)
|
3/7/2006 6:24:24 PM
|
|
Stefan Schulz wrote:
> Be careful, though, in both cases the field may be exposed to external
> viewers before being assigned, and this will have the most undesirable
> effect of having the "final" value change.
Hi,
can you show me an example of how the following field could
be exposed to an external viewer before the object being
constructed ?
How could any external viewer access a private instance field
before having a reference to the object ?
Roedy's (second) example
> private final int x;
>
> Constructor ( ) {
> x = something;
>}
|
|
0
|
|
|
|
Reply
|
neuneudr (93)
|
3/7/2006 6:32:00 PM
|
|
> public class A {
> private final int x;
> A() {
> new B(this);
> this.x = 42;
> }
> public int getX() {
> return x;
> }
> }
>
> public class B {
> public B(A a) {
> System.err.println(a.getX();
> }
> }
thanks!
|
|
0
|
|
|
|
Reply
|
neuneudr (93)
|
3/7/2006 7:16:37 PM
|
|
Hello again,
I added to "System.out" to your example and
ran it from IntelliJ IDEA...
41 appears in the color black at the console.
0 appears in red
43 appears in black.
Can somebody explain me what is going on?
(I realize that 0 appears because it hasn't
been initialized, but how does the console
notice that?)
class B {
public B(A a) {
System.out.println("41");
System.err.println(a.getX());
System.out.println("43");
}
|
|
0
|
|
|
|
Reply
|
neuneudr (93)
|
3/7/2006 7:27:58 PM
|
|
neuneudr@yahoo.fr wrote:
> Hello again,
>
> I added to "System.out" to your example and
> ran it from IntelliJ IDEA...
>
> 41 appears in the color black at the console.
> 0 appears in red
> 43 appears in black.
>
> Can somebody explain me what is going on?
> (I realize that 0 appears because it hasn't
> been initialized, but how does the console
> notice that?)
>
> class B {
> public B(A a) {
> System.out.println("41");
> System.err.println(a.getX());
^^^
> System.out.println("43");
> }
>
its more likely that the console is showing the output was to std Err
not std Out.
|
|
0
|
|
|
|
Reply
|
news248 (613)
|
3/7/2006 7:30:04 PM
|
|
neuneudr@yahoo.fr wrote:
>
> can you show me an example of how the following field could
> be exposed to an external viewer before the object being
> constructed ?
>
> How could any external viewer access a private instance field
> before having a reference to the object ?
public class A {
private final int x;
A() {
new B(this);
this.x = 42;
}
public int getX() {
return x;
}
}
public class B {
public B(A a) {
System.err.println(a.getX();
}
}
The this need not be explicit. Anonymous inner classes have an implicit
reference to the outer this, and are often created and released in
constructors.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
|
|
0
|
|
|
|
Reply
|
usenet120 (1481)
|
3/7/2006 7:32:15 PM
|
|
> > System.out.println("41");
> > System.err.println(a.getX());
> ^^^
> > System.out.println("43");
> > }
> >
> its more likely that the console is showing the output was to std Err
> not std Out.
:)
indeed!
|
|
0
|
|
|
|
Reply
|
neuneudr (93)
|
3/7/2006 7:43:52 PM
|
|
On 7 Mar 2006 11:27:58 -0800, neuneudr@yahoo.fr wrote, quoted or
indirectly quoted someone who said :
>41 appears in the color black at the console.
>0 appears in red
>43 appears in black.
Eclipse does the same thing.
System.err is red, System.out is black.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
|
0
|
|
|
|
Reply
|
my_email_is_posted_on_my_website (4730)
|
3/7/2006 10:44:39 PM
|
|
neuneudr@yahoo.fr wrote:
> Stefan Schulz wrote:
> > Be careful, though, in both cases the field may be exposed to external
> > viewers before being assigned, and this will have the most undesirable
> > effect of having the "final" value change.
>
> Hi,
>
> can you show me an example of how the following field could
> be exposed to an external viewer before the object being
> constructed ?
>
> How could any external viewer access a private instance field
> before having a reference to the object ?
static field:
class A1 {
private static final A1 instance;
static {
instance = new A1(new B1());
}
public static A1 getInstance(){
return instance;
}
/* ... */
}
class B1 {
public B1(){
A1 foo = A1.getInstance(); // <--- will return 0
/* ... */
}
/* ... */
}
non-static:
interface Priority {
int getPriority();
}
class A2 implements Priority {
private static PriorityList list = new PirorityList();
private final int priority;
public A2(int priority){
list.add(this);
this.priority = priority;
}
public int getPriority(){
return priority;
}
}
class PriorityList implements List<Priority> {
/* ... */
public boolean add(Priority a){ /* inserts at priority position */
int prio = a.getPriority(); // <--- will return 0
/* ... */
}
}
|
|
0
|
|
|
|
Reply
|
schulz.stefan (81)
|
3/8/2006 11:40:20 AM
|
|
|
17 Replies
50 Views
(page loaded in 0.174 seconds)
Similiar Articles: comp.lang.java.programmer - page 12Articles (51276) |<First << Prev /5128 Next>> Last >| Toward more efficient ArrayLists 10 2 (6/28/2003 5:23:05 AM) ... I use JBuilder 8 and have been looking around the ... Job Schedulers (preferably Open Source) - comp.unix.admin ...... into a Job Scheduler to replace extensive cron use on HP-UX and Linux systems. Last I ... after computation3 is ready Do some more ... We're working towards a fourth, "staging ... TGA /BMP to RGBA - Newbie - comp.graphics.api.opengl... png ..pnm ..raw ..sgi ..tga ..tif ..pal the import list is even more extensive. ... depth buffer is tested before the fragments are rasterized, which is the last ... how do you put images on a screen? - comp.lang.java.help ...... final String[] args) throws Exception { final ... drawImage(pacMan, x, y, this); // Do more ... This required extensive use of Java 2D and affine transforms. Unisys H/W failures - comp.sys.unisys... am looking for any known harware failures on DORADO-180 models, in last 5-10 ... It had much more extensive dynamic reconfiguration capabilities than the B6700 (which ... Phase versus Time from an FFT - comp.soft-sys.matlabThe last phrase makes no sense, w is not a phase. ... If you knew F and w*t how would you obtain phi? More ... As an Bob - don't use the FFT to extract time ... Future Terminal Emulator? - comp.unix.solaris... to dtterm for one or two things which make extensive use of ... like 15 years, I'll say... but, as of just the last ... > >In fact Solaris is likely to faulter even more ... reordering expressions with NaN - comp.lang.fortranThat would tend to push towards being more strict. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net ... Curvature of a 3D implicit function - comp.soft-sys.matlab ...... is there a formula that I can use ... I'm afraid my last class in differential geometry was some six decades ago, so the subject would require some extensive work on my part ... glDrawPixel - what is missing here? - comp.graphics.api.opengl ...The viewport is just a state and the very last step in the coordinate ... jpg ..pcx ..png ..pnm ..raw ..sgi ..tga ..tif ..pal the import list is even more extensive. New WinFilter Digital Filter design freeware tool release ...Hi all, I have just made the last release 0.7 of the ... It looks like I receive more spam in my beloved ... using standard techniques that don't require extensive ... Nonlinear curve fit fails to converge - comp.soft-sys.matlab ...The initial and final values are unknown but are ... Also note that I used obscenely more knots in this ... gives us understanding about Romeo's feelings towards ... 806 refusing to cooperate. - comp.dcom.sys.ciscoOne of the last things he asked me to do was 'upgrade my firmware' which I ... I would have thought that tan ISP would have done more extensive testing before ... Looking for a Tutorial or Presentation on "Knurling" - comp.cad ...... someone here please tilt me in the right direction towards ... However I did for job last year where I needed to make ... Presentation ... than a more friendlier and much more ... common email domain suffix - comp.mail.miscSplit full name in to first, middle, and last name ... in assembly - comp.lang.asm.x86... want to use 16-bit chips? 32-bit chips are more common ... and move more towards the ... Gianesin, Canepari and Partners - Media - We at GC&P strongly ...We plan to buy and use no more than 10 kilos of recycled ... but also transportation, usage, and final disposal. ... providers, who optimize their cargoes and make extensive use ... Social Security Boskin Commission Report - The United States ...Toward A More Accurate Measure Of The Cost Of Living. FINAL REPORT to the Senate Finance Committee ... and radio-TV category has been subject to more extensive ... 7/22/2012 3:31:16 AM
|