Skip to content

Instantly share code, notes, and snippets.

@jcavat
Created October 9, 2020 09:39
Show Gist options
  • Save jcavat/80570426acc61fd0f8ab508b401c84a3 to your computer and use it in GitHub Desktop.
Save jcavat/80570426acc61fd0f8ab508b401c84a3 to your computer and use it in GitHub Desktop.
Polymorphic nested classes
import java.time.LocalDate;
import java.util.function.Consumer;
public interface Status {
static class Running implements Status {
private Running() {
}
public boolean isRunning() {
return true;
}
public boolean isCancelled() {
return false;
}
public boolean isOutOfOrder() {
return false;
}
public String errorMessage() {
throw new IllegalStateException("state is running correctly!");
}
public LocalDate cancellationDate() {
throw new IllegalStateException("state is running correctly!");
}
public void apply(Runnable ifRunning, Consumer<LocalDate> ifCancelled, Consumer<String> ifOut) {
ifRunning.run();
}
}
static class Cancelled implements Status {
private LocalDate date;
private Cancelled(LocalDate date) {
this.date = date;
}
public boolean isRunning() {
return false;
}
public boolean isCancelled() {
return true;
}
public boolean isOutOfOrder() {
return false;
}
public String errorMessage() {
throw new IllegalStateException("state is cancelled. Error message couldn't exist!");
}
public void apply(Runnable ifRunning, Consumer<LocalDate> ifCancelled, Consumer<String> ifOut) {
ifCancelled.accept(this.date);
}
public LocalDate cancellationDate() {
return this.date;
}
}
static class OutOfOrder implements Status {
private String message;
private OutOfOrder(String message) {
this.message = message;
}
public boolean isRunning() {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isOutOfOrder() {
return true;
}
public String errorMessage() {
return this.message;
}
public LocalDate cancellationDate() {
throw new IllegalStateException("out of order state. Error message couldn't exist");
}
public void apply(Runnable ifRunning, Consumer<LocalDate> ifCancelled, Consumer<String> ifOut) {
ifOut.accept(message);
}
}
boolean isRunning();
boolean isCancelled();
boolean isOutOfOrder();
String errorMessage();
LocalDate cancellationDate();
void apply(Runnable ifRunning, Consumer<LocalDate> ifCancelled, Consumer<String> ifOut);
static Status running() {
return new Running();
}
static Status outOfOrderState(String error) {
return new OutOfOrder(error);
}
static Status cancelledState(LocalDate cancellationDate) {
return new Cancelled(cancellationDate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment