Bruno Mazzardo Bruno Mazzardo - 1 year ago 86
Java Question

Prevent a construction of instance with an invalid argument

I have a constructor that receives an

of routes:

public Voo(ArrayList<Routes> routes, LocalDateTime dateTime, Duration duration) {
if (routes.isEmpty()) {


this.routes = routes;
this.dateTime = dateTime;
this.duration = duration;
this.status = Status.CONFIRMED;

How can I prevent the constructor from returning an instance of
if the
received is empty?

Answer Source

Typically an IllegalArgumentException is thrown. e.g.

if (routes.isEmpty()) {
    throw new IllegalArgumentException("routes should be non-empty");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download