Similar to valueOf, the instanceof keyword provides an opportunity to circumvent the type-checking system of the Java compiler. Their inclusion in an application should be considered a code smell and is indicative that we have a String that should be represented by another data type. Therefore, when possible, we should avoid using valueOf methods that convert a String to some primitive value, including: Notice, though, we have to make a conscious decision about what value to set accountValue to when a non- long is provided, even though one should never be provided in the first place. Instead, we should change our JSON to properly represent our intent: The type of our accountValue field is a String, and nothing stops a user that is unfamiliar with our application from rightly setting accountValue to a String. We would be wrong for thinking that, though, since nowhere in our JSON or even in our code is it documented that a long is expected. We may be tempted to think that this is not possible since everyone must surely know that an account value is a number. Instead of allowing the compiler to perform static type-checking analysis on the source code of our program, we have instead deferred this check to runtime, where Long.valueOf is now responsible for implementing the type-checking.Įven if we attempt to catch this NumberFormatException in our getAccountValue method, we are now responsible for deciding on what to do when we encounter a number that is not a convertible to a long. Instead, during execution, an exception was thrown when "unknown" was passed to Long.valueOf, causing our application to abruptly exit.ĭue to our decision to represent accountValue as a String, we have now delayed our type checking from compile-time to runtime. It is crucial to note that this exception occurs at runtime, not compile-time: The compiler did not have enough information during compilation to deduce that the value provided to Long.valueOf was not going to be a String that it could safely convert to a long. For example, we can define an Address class and instantiate a variable with a specific Address state: With the introduction of Object-Oriented Programming (OOP), we can define new natures by creating classes and instantiating objects of that class. By applying a type to every piece of data, we make an explicit statement about the nature of that data.įor example, if we define a variable as having a type of int, we state that the variable cannot be larger than 2 31 - 1 and cannot be less -2 31. One of the most significant benefits of strongly-typed languages like Java is that the compiler can enforce our intentions at compile-time.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |