I have the following exercise:
Define a class named circle that accepts objects of type point, and calculates their distance from the center of the circle. If the point is outside the circle should be sent notices of exception.
This is my code:
class Point
{
protected int x,y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
}
class Circle : Point
{
public Circle(Point p,int radius):base(3,5)
{
}
}
class Program
{
static void Main(string[] args)
{
}
}
I don’t know what I have to do in the circle class, how can I know if the point is in the circle or not?
Thanks everyone.
Inheritance vs. composition: First, it seems wrong that your class
Circlederives fromPoint, just because you need anxandycoordinate pair for your circle, too. Remember that inheritance usually models “is-a” relationships. But circles are not points. Rather, it could be said that they can be defined through a point (the center) and a radius. Thus it would be more logical to use composition (“has-a” relationship):When to use exceptions (and when not to): Second, I hope that whoever gave you the exercise didn’t actually mean to
throwan exception just because your distance-calculating method got aPointthat lies outside the circle. I would consider this use of exceptions invalid. Exceptions ought to be used in circumstances where some condition occurs that your code cannot properly deal with. However, calculating a distance between two points can never fail (unless perhaps for weird floating-point issues like overflow or underflow):If suddenly such a method threw an exception, many users of your code might consider this unlogical. Why should that method go beyond what its name suggests, and throw an exception just because the distance is greater than
radius?It would be more advisable IMO to introduce a second method:
Now you have two methods that both do just what most people would expect, don’t throw unexpected exceptions, and still offer all the functionality that you’ll most likely need.
P.S.: Reading my answer many days later, it suddenly strikes me that it would be better still to define the two methods shown above on the
Pointclass instead, e.g.:… which results in easier-to-understand code; e.g.
somePoint.LiesWithin(someCircle)instead ofsomeCircle.LiesWithinCircle(somePoint).