Java 7 introduced a bunch of language improvements (known as Project Coin). One of the improvement that I want to focus on is an underscore in numeric literals.
Since Java 7 we can type:
int a = 10_000;
What's the idea which stands behind that? The answer is simple - readability. The first thing that came to my mind was the usage in big values to separate decimal parts, e.g.:
int million = 1_000_000;
However, I have recently found one more interesting use case for that feature. In the project that I'm currently working on there is a concept of error codes. Let's say that there are two operations: validate and save. For each operation there can be a couple of errors with specific codes, e.g. validate (invalid value, duplicated value). I realized that the following approach to error codes is quite readable:
public static final int VALIDATE_INVALID_VALUE = 100_000; public static final int VALIDATE_DUPLICATED_VALUE = 100_001; public static final int SAVE_DATABASE_ERROR = 101_000;
The part on the left underscore side is the family number (100 - validate, 101 - save) and the part on the right side is a specific exception. Thanks to that we have exception codes that are grouped logically. I really like this approach.
No comments :
Post a Comment