Guest User

Untitled

a guest
Jul 22nd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. # Sad Compiler
  2.  
  3. Overall, Java's compiler is an impressive piece of software (not nearly as impressive as the JVM, though) that has no doubt saved me from countless hours hunting down runtime issues. Nevertheless, there are times when the compiler makes me sad.
  4.  
  5. ## Lack of Flow Typing
  6. ```java
  7. if (obj instanceof Foo) {
  8. ((Foo) obj).foo();
  9. }
  10. ```
  11. **Why it's sad:** given improvements in the compiler's type inferrence ability, it would seem within reason to support flow-sensitive typing. If the condition that `obj` is an instance of Foo proves true, this information should "flow" into the `if` body. But no, the compiler still requires an explicit cast on the object in order to use the methods of the Foo type. If you’re a JVM user desperate for flow-sensitive typing, check out Kotlin (or Ceylon).
  12.  
  13. ## The Elusive Switch Default
  14. boolean elusiveSwitchDefault(DayOfWeek day) {
  15. switch (day) {
  16. case SUNDAY:
  17. case MODNAY:
  18. case TUESDAY:
  19. case WEDNESDAY:
  20. case THURSDAY:
  21. case FRIDAY:
  22. case SATURDAY:
  23. return true;
  24. default:
  25. return false;
  26. }
  27. }
  28.  
  29. **Why it's sad** Clearly, all possible values of the `DayOfWeek` enumeration are being accounted for in the case statement, therefore there is never an occassion for the `default` statement to execute.
  30. **Why it's not that sad** First off, enumerations may change over time. If your switch statement is compiled prior to a new enum value being added, then all of a sudden there is a possibility the `default` case would execute.
  31.  
  32. ## The Impossible Else
  33. ```java
  34. int impossibleElse(boolean condition) {
  35. if (condition) {
  36. return 1;
  37. } else if (!condition) {
  38. return 2;
  39. } else {
  40. return 3;
  41. }
  42. }
  43. ```
  44. ## Ternary Auto-Unboxing Nastiness
  45. ```java
  46. boolean nasty(Object obj) {
  47. return obj == null ? null : true;
  48. }
  49. ```
  50. **Why this is sad?** This shouldn't even compile, in my opinion. Clearly one part of the ternary operator evaluates to a primitive--why should it be allowed that the other path be `null`? Because it does, when the compiler tries to auto un-box the resulting null `Boolean` into a primitive `boolean`, null pointer exception hilarity ensures.
Add Comment
Please, Sign In to add comment