Bruno Mazzardo Bruno Mazzardo - 3 months ago 12
Java Question

Prevent a construction of instance with an invalid argument

I have a constructor that receives an

ArrayList
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
Voo
if the
routes
received is empty?

Answer

Typically an IllegalArgumentException is thrown. e.g.

if (routes.isEmpty()) {
    throw new IllegalArgumentException("routes should be non-empty");
}