3 ms·
This is slightly random, but I couldn't help but "laugh in Java" when the very first feature shown, `Objects.requireNonNullElse`, is given with an example and t
by hn_throwaway_99 2y ago
This is slightly random, but I couldn't help but "laugh in Java" when the very first feature shown, `Objects.requireNonNullElse`, is given with an example and text that states "This method helps streamline handling null values, removing the need for verbose null checks ." Except the version that uses `Objects.requireNonNullElse` is longer than the one that uses the ternary operator!
What is it with Java deciding "Why use 2 characters when 40 will do?" Is it to much to ask for a ?? or ?: operator?
- Strilanc 2y agoAh, but the ternary operator solution requires repeating the name of the variable twice. And obviously, since you're writing in Java, your variable name will be at least 50 characters long. Thus making `Objects.requireNonNullElse` shorter.
- Glant 2y agoThe null coalescing operator (??) works well for this
- hn_throwaway_99 2y agoExactly, which is why it's baffling that Java doesn't have it.
- Igor_Wiwi 2y agoIt's not only about the length of the method. Ternary operators may look simple enough, but they could lead to some subtle errors. For example, try to guess what's wrong with this code: List<String> trimAndAdd(List<String> input, String newItem) { List<String> result = new ArrayList<>(input.size() + newItem == null ? 0 : 1); ...