Reputation: 123
I am trying to implement a class which accepts multiple Points to construct a polygon.
By creating a constructor accepting a variadic amount of arguments, in this case point objects from the built-in class Point
, I am certain that the arguments that are provided can construct a polygon.
However I also want to be able to construct a polygon using only integers (x1, y1, x2, y2)
. If someone provides the constructor with an illegal amount of arguments, then something should happen.
What is the best way to deal with this case? Should I throw an exception or is there a more appropriate way to deal with this situation? I would like to know your opinion!
Upvotes: 0
Views: 60
Reputation: 140326
I think that it is better to make this into a compile-time failure rather than a runtime failure, by pairing together the coordinates in a point class before passing to your constructor:
Polygon(Point... pts) {
// ...
}
E.g. using the java.awt.Point
class, or one you have written yourself. Now, you don't need to check anything about the argument (except maybe that it is null or contains null elements), since presumably any number of vertices is acceptable.
Aside from the advantage of you knowing that your coordinates are correctly specified at compile time, you also get the readability advantage of seeing how the coordinates are grouped together. E.g.
...3, 7, 8, 9, 1255, ...
Here, is 8
an x or a y coordinate? It is much easier to tell if you were to write:
... pt(3, 7), pt(8, 9), pt(1255, ...), ...
(Where pt
is a factory method to create the point).
Upvotes: 1
Reputation: 1803
You can use a varargs collection of parameters in your constructor, and then check if the number of parameters supplied is divisible by 2 (or 3, if you're using 3D polygons).
public class Polygon
{
public Polygon(int... coords)
{
if (coords.length % 2 != 0)
throw new InvalidParameterException("Polygon constructor must have coordinates in pairs");
// If you reached here, coords has valid length.
// Process normally.
}
}
To answer your question of what the appropriate response is, that depends on the application. Personally, I would throw the exception (like I did in my sample above) because without a valid number of points, the Polygon cannot be constructed, which is a serious problem.
Another way I might consider implementing the class is to throw out the last argument (so that there is an even number) and construct the Polygon using only the valid arguments. Of course, this is somewhat dangerous since the user of the class doesn't know that they supplied the wrong number of arguments.
Upvotes: 1
Reputation: 7189
You should throw an IllegalArgumentException, you can check the documentation
Upvotes: 1