Beautiful Code…
Chapter 1: Arguments and Parameters
An argument is a value or expression passed as input to a method, and a parameter is a variable defined within the method to hold this input.
In Java, a null value represents the absence of a value, and attempting to perform operations on a null value parameter will result in a NullPointerException.
Similarly, if a method returns a null value, the caller should handle it appropriately to avoid a NullPointerException. However, it is generally recommended to avoid returning null values whenever possible.
Let’s take a look at the example method…
Will this fail at compile time? No
Will it fail at runtime? Yes
- An array can be null or empty. In this case, if the array is not of primitive type but a wrapper class, we need to check if any item in the array is null. If a null value is found, returning null is appropriate as the argument is considered invalid.
- The for loop will throw a NullPointerException if any element of the array is null when using a primitive type for the loop variable.
- Returning null should be avoided when possible. If the returned value is reassigned to a primitive type at the caller side, it will result in a NullPointerException.
Possible Solution
- Encapsulate the logic within a try-catch block and throw an IllegalArgumentException to handle the invalid argument case.
- Modify the for loop variable to be of type Double rather than double, allowing for null values. Additionally, a null check can be added inside the loop to handle any null values encountered.
Both have their drawbacks. The first introduces overhead by requiring an additional exception-handling block on the caller’s side. The second is not ideal either, as it adds extra validation within the loop and still returns null at the end. However, if the method is dealing with a large array of 100K elements, and the last element happens to be null, it would require iterating through the entire array before returning null.
Best Solution
- Make the parameter type primitive, as this would result in a compile-time error if anyone attempts to pass a null value as an argument. By doing so, the need for extra validations can be eliminated.
- Utilize Optional instead of returning null. The Optional provides a more explicit and robust way of handling the potential absence of a value, allowing for clearer code and avoiding NullPointerException.
Let’s take a look at the revised method…
See the difference, now this method is free from any kind of RuntimeException.