Java - Unique Enum Field values
When you have a Java Enum with a field, a requirement can be that the field value needs to be unique. Using a utility method it can be easy to create a test for this. Given an Enum class with a field (using some Lombok):
@Getter
@RequiredArgsConstructor
@Accessors(fluent = true)
public enum Sides {
LEFT("left"),
RIGHT("right");
final String label;
}
You can enforce uniqueness using a unit test:
import io.vavr.collection.HashMap;
import io.vavr.collection.Vector;
import org.junit.jupiter.api.Test;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SidesTest {
@Test
void unique() {
assertUnique(Sides.values(), Sides::label);
}
private static <T> void assertUnique(T[] values, Function<T, String> fieldValue) {
assertEquals(
HashMap.empty(),
Vector.of(values)
.groupBy(fieldValue)
.filter(it -> it._2().size() > 1));
}
}
The test will automatically validate that all fields have distinct values, even if the Enum expands or changes in the future. Failures will report the enum values that have the same property. If we misconfigure the enum above ( RIGHT("left")
) we see which value occurred multiple times, and in which Enum values:
Shell - Switch Statements
Recently I had to work a bit more than usual on shell scripting, and had to do a bunch of switches. I used this also in the scripts for this project. A simplified impression shows how we can match user input with supported commands:
#!/bin/sh
CMD=$1
case "$CMD" in
"run") echo "cmdRun" ;;
"publish") echo "cmdPublish" ;;
*) echo "Unknown command $CMD"; exit 1 ;;
esac
This way we can match the provided input with supported cases ("run"
and "publish"
), and error otherwise (*
). The double semicolon (;;
) marks the end of a case.
Java - Error Return Types
Writing code assuming everything will follow the happy path may not result in the best software quality or user experience. Sometimes we choose to ignore unhappy paths, or lack awareness of the existence of unhappy paths. Both of these scenarios can lead to runtime bugs and problems for customers which may be good to prevent.
Many strategies and coding styles exist in different languages to give the developer tools to address this issue. In this post I’d like to explore some of them and illustrate my preferences.