-
-
Save eneveu/4596800 to your computer and use it in GitHub Desktop.
DSL to build an enum hierarchy in a visually elegant way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rubber.duck; | |
import com.google.common.collect.ImmutableSet; | |
public enum Foo implements FooHierarchy.Node { | |
ONE, | |
TWO, | |
THREE, | |
FOUR, | |
FIVE, | |
SIX, | |
SEVEN; | |
@Override | |
public FooHierarchy.Node withChildren(FooHierarchy.Node... children) { | |
return new FooHierarchy.NodeWithChildren(this, ImmutableSet.copyOf(children)); | |
} | |
private static final FooHierarchy.Node hierarchy = | |
ONE.withChildren( | |
TWO.withChildren( | |
THREE, | |
FOUR.withChildren( | |
FIVE | |
) | |
), | |
SIX, | |
SEVEN | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rubber.duck; | |
import com.google.common.collect.ImmutableSet; | |
import javax.annotation.Nonnull; | |
public class FooHierarchy { | |
public interface Node { | |
Node withChildren(Node... children); | |
} | |
public static class NodeWithChildren implements Node { | |
@Nonnull | |
final Node element; | |
@Nonnull | |
final ImmutableSet<Node> children; | |
NodeWithChildren(@Nonnull Node element, @Nonnull ImmutableSet<Node> children) { | |
this.element = element; | |
this.children = children; | |
} | |
public Node withChildren(Node... children) { | |
throw new UnsupportedOperationException("Cannot add children to a node that already has children"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment