Re: compiler question
- From: Maarten Bodewes <maarten.bodewes@xxxxxxxxx>
- Date: Mon, 30 Jun 2008 01:19:36 +0200
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.
Regards,
Maarten
.
- Follow-Ups:
- Re: compiler question
- From: John B. Matthews
- Re: compiler question
- From: Arne Vajhøj
- Re: compiler question
- References:
- compiler question
- From: ankur
- Re: compiler question
- From: Roedy Green
- compiler question
- Prev by Date: Re: Timer Schedule TimerTask for same hour every day
- Next by Date: Re: compiler question
- Previous by thread: Re: compiler question
- Next by thread: Re: compiler question
- Index(es):
Relevant Pages
|