Information Technology Reference
In-Depth Information
This sample shows what I mean by substitutability: A circle has been sub-
stituted for an ellipse. The ComputeArea function works even with the
substitution. You got lucky. But examine this function:
public static void Flatten( Ellipse e)
{
e.R1 /= 2 ;
e.R2 *= 2 ;
}
// call it using a circle:
Circle c = new Circle ( new PointF ( 3.0f , 0 ), 5.0f );
Flatten(c);
This won't work. The Flatten() method takes an ellipse as an argument.
The compiler must somehow convert a circle to an ellipse. You've created an
implicit conversion that does exactly that. Your conversion gets called, and
the Flatten() function receives as its parameter the ellipse created by your
implicit conversion. This temporary object is modified by the Flatten()
function and immediately becomes garbage. The side effects expected
from your Flatten() function occur, but only on a temporary object. The
end result is that nothing happens to the circle, c.
Changing the conversion from implicit to explicit only forces users to add
a cast to the call:
Circle c = new Circle ( new PointF ( 3.0f , 0 ), 5.0f );
Flatten(( Ellipse )c);
The original problem remains. You just forced your users to add a cast to
cause the problem. You still create a temporary object, flatten the tempo-
rary object, and throw it away. The circle, c, is not modified at all. Instead,
if you create a constructor to convert the Circle to an Ellipse, the actions
are clearer:
Circle c = new Circle ( new PointF ( 3.0f , 0 ), 5.0f );
Flatten( new Ellipse (c));
Most programmers would see the previous two lines and immediately real-
ize that any modifications to the ellipse passed to Flatten() are lost. They
would fix the problem by keeping track of the new object:
Circle c = new Circle ( new PointF ( 3.0f , 0 ), 5.0f );
Flatten(c);
 
Search WWH ::




Custom Search