3 ms·
laughs in Java, where enums ARE polymorphic classes
by brazzy 5y ago
laughs in Java, where enums ARE polymorphic classes
- marginalia_nu 5y agoI find this pattern pretty useful when you have a lot of small utility programs and don't want to litter the code 36 different main classes. Like it's a frickin bizarre pattern, but it's undeniably pretty tidy. enum ToolLauncherMain { convertTheThing(this::doFoo, "Convert the bin to the dat"), sendSomeMessage(this::doBar, "Pass a message to the stuff-doer"), help(this::printHelp, "Print this message"); private final Consumer<String[]> runner; private String description; public UtilRunner(Consumer<String[]> r, String desc) { runner = r; description = desc; } public static void main(String... args) { try { valueOf(args.length == 0 ? "help" : args[0]).runner.apply(args); } catch (IllegalArgumentException ex) { printHelp(); } } private void printHelp() { for (var value : values()) { System.out.printf("%s - %s\n", value, value.description); } } // ... }