Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA - - - Consider this code a.method( b.expensive(c) ); where a is an instance

ID: 3854470 • Letter: J

Question

JAVA - - - Consider this code a.method( b.expensive(c) ); where a is an instance of Aclass which has a method called method() that rarely uses its parameter. The object b is an instance of Bclass which has a very expensive method called expensive; this method takes one parameter of class Cclass and returns a value of class Eclass.

The declaration for method() begins method(Eclass e). Later, it contains the code if(unlikely)use(e); where use() is some other method in the same class.

a) You could just rewrite method() so that it is called as a.method(b, c); passing the parameters b and c without evaluating expensive(), thus avoiding wasted computation. Assume this rewrite and give the declaration for the parameters to method() and the new version of the code in the if(unlikely) statement.

b) The above solution to avoiding wasted computation could create problems. Demonstrate the difficulties this would create by describing at least one legal calls to method() that would be difficult to rewrite to take advantage of the rewritten version of method() from part a.

Explanation / Answer

a)

Aclass

{

method( Bclass b, Class c)

{

if(unlikely) use(b.expensive(c));

// this helps to reduce wastage since expensive is called only when this unlikely if is true.

}

}

b) suppose our Aclass method() invokes lots of other methods which uses object e as their parameters then indeed we will be wasting a lot of time computing b.expensive(c).To understand it completely see example below.

eg.

Aclass

{

method( Bclass b, Class c)

{

if(unlikely) use(b.expensive(c));

use2(b.expensive(c));

use3(b.expensive(c));

use4(b.expensive(c));

// we are invoking method expensive multiple times which wastes a lot of computation time.

}

use(Eclass e){// do something on e}

use2(Eclass e){// do something on e}

use3(Eclass e){// do something on e}

use4(Eclass e){// do something on e}

}

so this is one scenario where our part A version of method() will cause difficulty while computing.