Re: compiler question



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
.



Relevant Pages

  • Re: compiler question
    ... if (somethingoroother) assign price ... thePrice = weight*10;} ... Note that I would not use two assignments in one line, it's less readable and harder to work with in the debugger. ...
    (comp.lang.java.programmer)
  • Re: compiler question
    ... if (somethingoroother) assign price ... thePrice = weight*10;} ... Note that I would not use two assignments in one line, it's less readable and harder to work with in the debugger. ...
    (comp.lang.java.programmer)
  • Re: compiler question
    ... You are presuming greater intelligence of the compiler than it has. ... if (somethingoroother) assign price ... thePrice = 1000; ...
    (comp.lang.java.programmer)
  • Re: Calculating values defined by their #
    ... FROM [SELECT TOP 2 PRICE AS THEPRICE FROM PRICES ORDER BY MYDATE DESC]. ... Following up on my last comment, and OT to the thread, it seems Access wants to create an alias for the subquery. ... Though Access changes it to: ...
    (comp.databases.ms-access)