Re: compiler question
- From: Maarten Bodewes <maarten.bodewes@xxxxxxxxx>
- Date: Mon, 30 Jun 2008 21:05:43 +0200
Arne Vajhøj wrote:
Maarten Bodewes wrote:Roedy Green wrote:Sun, 29 Jun 2008 11:25:56 -0700 (PDT), ankur
<ankur.a.agarwal@xxxxxxxxx> wrote, quoted or indirectly quoted someone
who said :
if (weight < 10) thePrice = 1000;
if (weight > 50) thePrice = 5000;
if (weight >= 10) thePrice = weight*10; // Always
executed.
System.out.println("The price is: " + thePrice); // (1)
You are presuming greater intelligence of the compiler than it has.
Is sees this blurrily something ilke
if ( somethingoroother ) assign price
if ( somethingelse ) assign price
if (yetanothingh thing) assign price
Had you written this as:
if (weight < 10)
{
thePrice = 1000;
}
else if (weight > 50) { thePrice = 5000;
}
else
{
thePrice = weight*10; }
Then it could be absolutely sure thePrice will be assigned. It does
not have to analyse the conditional expressions to know this.
Yup, and to be sure that your variable will only be assigned precisely once, create it using the final keyword.
final int thePrice;
if(..) thePrice = 1;
else thePrice = 2;
This will throw a compiler error whenever thePrice is not assigned, or when thePrice is assigned a second time. Much more secure.
Note that I would not use two assignments in one line, it's less readable and harder to work with in the debugger.
When it comes to style I would recommend Java Coding Convention
from SUN.
The above is not compliant.
Absolutely! My only possible way of explaining myself is not having the Eclipse checkstyle plugin working on my Thunderbird client :)
Maarten
.
- References:
- compiler question
- From: ankur
- Re: compiler question
- From: Roedy Green
- Re: compiler question
- From: Maarten Bodewes
- Re: compiler question
- From: Arne Vajhøj
- compiler question
- Prev by Date: Re: java tutorial available for download
- Next by Date: Re: Visual Mapping Source
- Previous by thread: Re: compiler question
- Next by thread: Re: compiler question
- Index(es):
Relevant Pages
|